如果在FormArray中不同的FormGroup下,为什么FormControlName复制值

时间:2019-08-05 07:27:34

标签: angular typescript angular-reactive-forms

因此,我有一个反应式表单,其中使用了某些FormGroup(与名字和姓氏联系),并将它们加到FormArray中。但是,每次我更新其中一个具有明显相同名称(firstName,lastName)值的FormControls中的值时,整个FormArray FormGroup FormControls中的值都会被更新。 我在做什么错了?

contact = new FormGroup
  ({
    firstName: new FormControl(),
    lastName: new FormControl()
});

this.form = this.fb.group({
  name: ['', Validators.required],
  contacts: this.fb.array([
    this.contact
  ])
});

我想根据需要向FormArray添加尽可能多的联系人FormGroup,并保留其FormControlName,但最终使用唯一的对应值填充Form值。

1 个答案:

答案 0 :(得分:2)

似乎您要向formArray多次添加相同的formGroup实例。 每次添加到formArray时,您都需要创建一个新的formGroup实例:

export class ContactForm extends FormGroup{ 
        constructor(){
            super({
              firstName: new FormControl(),
              lastName: new FormControl(),
            });
     }
    }

然后再说:

this.form = this.fb.group({
      name: ['', Validators.required],
      contacts: this.fb.array([
        new ContactForm(),
      ])
    });