Angular2 patchValue将值推入数组 [英] Angular2 patchValue push value into array

查看:266
本文介绍了Angular2 patchValue将值推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是看起来像Angular2的

Is it It looks like Angular2's FormGroup.patchValue() doesn't push new elements into an array.

例如这样的东西:

ngOnInit() {

    this.form = this.formBuilder.group({
        animal: [''],
        school: this.formBuilder.group({
            name: [''],
        }),
        students: this.formBuilder.array([this.formBuilder.control('Bob')])
    });

    setTimeout(() => this.form.patchValue({
      animal: 'cat'
      school : {name: 'Fraser'},
      students: ['Bob gets edited', 'This will not show']
    }), 250);

}

更新学生"中的第一个元素,但不会插入第二个元素.

Will only update the first element in "students" but it will not insert the second element.

我要怎么做才能显示两个元素?

What would I need to do to make it display both elements?

在此处插入.

推荐答案

.patchValue()仅更新现有的FormArray,不会修改表单模型的结构.

.patchValue() only updates the existing FormArray, it won't modify the structure of your form model.

patchValue(value:any [],{onlySelf,glowEvent} ?: {onlySelf ?:布尔值, embedEvent ?: boolean}):void修补FormArray的值.它 接受与控件结构匹配的数组,并将 尽力使这些值与组中的正确控件匹配.

patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.

它接受数组的超集和子集,而不会抛出 错误.

It accepts both super-sets and sub-sets of the array without throwing an error.

实际上,您需要将一个新元素推入到数组中,以使其出现.

You actually need to push a new element onto the array in order for it to appear.

 this.form.controls['students'].push(new FormControl('This will not show'));

这一切在FormArray文档 https中://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html

这篇关于Angular2 patchValue将值推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆