Nested groups in Angular2 forms?

我怕爱的太早我们不能终老 提交于 2019-12-08 13:29:16

问题


I'm using the reactive forms module in Angular 2 to create a form with several nested groups.

My 'trust' form has an array of contacts at

<FormArray>this.newTrustForm.controls['contact']

One of the fields in the 'contact' group is an array of 'email' groups and I tried finding it here, but alas, no. Where would I then find it?

<FormArray>this.newTrustForm.controls['contact'].controls['email']

I setup my form with the following.

constructor(private _fb: FormBuilder) { }

ngOnInit() {
  this.newTrustForm = this._fb.group({
    ...
    contact: this._fb.array([]),
    ...
  });
}

I then add 'contact' groups with the following.

initContact() {
  return this._fb.group({
    ...
    email: this._fb.array([]),
    ...
  });
}

And then I have initContactEmail setup in the same way.


回答1:


You have specify the index of contact:

<FormArray>this.newTrustForm.controls['contact'][INDEX]['controls']['email']

Or (more readable):

this.newTrustForm.get(`contact.${INDEX}.email`) as FormArray;

Also, as a suggestion, since contact and email are arrays, you could named them in plural: contacts and emails.



来源:https://stackoverflow.com/questions/42558329/nested-groups-in-angular2-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!