Reactive Forms: How to add new FormGroup or FormArray into an existing FormGroup at a later point in time in Angular 7

∥☆過路亽.° 提交于 2019-11-27 05:30:21

FormGroup addControl method accepts AbstractControl as parameter which can be either a FormControl or a FormArray or another FormGroup as they all extend AbstractControl.

class FormGroup extends AbstractControl
...
class FormControl extends AbstractControl
...
class FormArray extends AbstractControl

FormBuilder can help you building such controls with array() and group() methods:

this.myForm = this.fb.group({
  id: this.fb.control([this.book.id]),
  authors: this.fb.array(['George Michael', 'Aretha Franklin']),
  metaData: this.fb.group({ description : 'Great Book', publication: 2019})
});

You still can use the factory afterwards to build the controls you need (no matter what kind of control it is):

this.myForm.addControl('authors', this.fb.array(['George Michael', 'Aretha Franklin']))
this.myForm.addControl('metaData', this.fb.group({ description : 'Great Book', publication: 2019}))

You can simply pass the FormArray instead of a FormControl.

this.form.addControl('arr',this.fb.array([]));

Edit: To use existing value

To use the value from the authors array, use this:

authors.forEach(author => {
  (<FormArray>this.form.controls.arr).push(new FormControl(author));
});

OR

this.myForm.addControl('authors', this.fb.array(['George Michael', 'Aretha Franklin']))

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