fivedoor fivedoor - 2 months ago 31
AngularJS Question

Angular2: add and submit a new formGroup name and values with model driven form

Adding to a FormArray via input field

To add values, via a form input, to an existing array I can use (click)="addAddress()" in the html where addAddress is defined in the component.ts to update values in an array in the form AppComponent:

ngOnInit() {
this.myForm = this._fb.group({
name: ['', [Validators.required, Validators.minLength(5)]],
addresses: this._fb.array([
this.initAddress(),
])
});
}

initAddress() {
return this._fb.group({
street: ['', Validators.required],
postcode: ['']
});
}

addAddress() {
const control = <FormArray>this.myForm.controls['addresses'];
control.push(this.initAddress());
}


And back in the html ngFor is used to add a set of input fields each time the 'add' button is clicked":

<div formArrayName="addresses">
<div *ngFor="let address of myForm.controls.addresses.controls; let i=index" >
<span>Address {{i + 1}}</span>
<div [formGroupName]="i">
<input type="text" formControlName="street">
<input type="text" formControlName="postcode">
</div>
</div>
</div>


Like the full working example here: https://embed.plnkr.co/sUjE1ULYhfDHLNBw2sRv/1

Adding to form FormGroup via input field

I would like to understand how to add a completely new FormGroup via form input.
So taking the case of the example above...

Rather than adding to an array of addresses:

{
"name": "",
"addresses": [
{
"street": "Baker Street",
"postcode": "w2"
},
{
"street": "Bond Street",
"postcode": "w1"
}
]
}


Each time an address is added a new FormGroup is created where the user adds the FormGroupName for each via form input. For example:

{
"name":"",
"home":{
"street":"Baker Street",
"postcode":"w2"
},
"work":{
"street":"Bond Street",
"postcode":"w1"
}
}

Answer

Using the addControl method this can be achieved like so:

app.component.html excerpt:

        <div class="margin-20">
            <a (click)="addGroup(newName.value)" style="cursor: default">Add Group +</a>
          </div>

app.component.ts excerpt:

ngOnInit() {

        this.myForm = this._fb.group({    
        });
    }


 addGroup(newName:string) {

         let data = this._fb.group({
                     foo: ['what a load of foo'],
                     bar: ['see you at the bar']

                    })

        this.myForm.addControl(newName, data);
        document.getElementById('newName').value='';


    }

Working example in this plunk:

For an example where a corresponding input field is published for each formControl that is added in the new named group I created this plunk