在将FormControl添加到表单组中有疑问吗?

时间:2019-06-13 16:57:11

标签: angular

嗨,我有5个角度项目代码中的小代码段。

this.recipients.forEach(recipient => {
      return new FormControl(recipient, this.validators);
    });

    this.formGroup.updateValueAndValidity();

在代码接收者中,这里是一个string数组。从代码中,我可以看到我们正在遍历数组,创建一个表单控件。然后我们调用updateValueAndValidity()。我的问题是如何将表单控件添加到表单组中? 非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我想你想说

//NOT WORK
myForm=new FormGroup({}) //create a empty formControl
this.recipients.forEach(recipient => {
   myForm.addControl("name",new FormControl(recipient, this.validators));
});

好吧,我们需要给一个“不同的名字”

myForm=new FormGroup({}) //create a empty formControl
this.recipients.forEach((recipient,index) => {
   myForm.addControl("name"+index,new FormControl(recipient, this.validators));
});

但是您可以创建一个FormArray

myFormArray=new FormArray([]) //create a empty formArray
this.recipients.forEach(recipient => {
   myForm.push(new FormControl(recipient, this.validators));
});

controls:FormControl[]=[]    //create a empty Array of FormControls
this.recipients.forEach(recipient => {
   controls.push(new FormControl(recipient, this.validators));
});
myFormArray=new FormArray(controls) //create a formArray with the controls

可以使用“ map”(不是forEach)编写最后的代码。 “ map”返回一个数组“转换”

myFormArray=new FormArray(
     this.recipients.map(recipient => {
            return new FormControl(recipient, this.validators)
     })
);