Lon*_*ely 5 angular angular-reactive-forms formarray formgroups
In the other examples at StackOverflow there are many questions about using FormGroups in FormArrays. But my question is the opposite.
FormArrays have a push method, that makes many things possible. FormGroups have indeed an addControl method for adding simple FormControls. Afaik FormGroups do not have addFormArray or addFormGroup method. Therefore I need your help.
Following situation:
this.myForm = this.fb.group({
id: this.fb.control([this.book.id]),
// or short form `id: [this.book.id],`
});
Run Code Online (Sandbox Code Playgroud)
Adding a simple control at a later point in time is easy:
this.myForm.addControl('isbn', this.fb.control(this.book.isbn));
Run Code Online (Sandbox Code Playgroud)
But what about adding FormArrays and FormGroups into an existing FormGroup? For instance, I would like to use the following array and object for this purpose:
const authors = ['George Michael', 'Aretha Franklin'];
const metaData = { description : 'Great Book', publication: 2019}
Run Code Online (Sandbox Code Playgroud)
I would like to add authorsArray or metaData only then if they are existing. That's the reason, why I want to add them at a later time.
p.s. Please ignore the validation rules.
Gré*_*mer 10
FormGroup addControl方法接受AbstractControl作为参数,可以是 aFormControl或 aFormArray或另一个,FormGroup因为它们都扩展了AbstractControl。
class FormGroup extends AbstractControl {}
class FormControl extends AbstractControl {}
class FormArray extends AbstractControl {}
Run Code Online (Sandbox Code Playgroud)
FormBuilder可以帮助您使用array()和group()方法构建此类控件:
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})
});
Run Code Online (Sandbox Code Playgroud)
之后您仍然可以使用工厂来构建您需要的控件(无论它是哪种控件):
this.myForm.addControl('authors',
this.fb.array(['George Michael', 'Aretha Franklin']))
this.myForm.addControl('metaData',
this.fb.group({description: 'Great Book', publication: 2019}))
Run Code Online (Sandbox Code Playgroud)