I use the recently released 2.0.0 Angular, basically I have a component that initializes the values of my form template, which consists of an input text field, and formArray from a FormGroup with two input text fields.
When initialization is done, the binding works fine, but when I click the new FormGroup on formArray, the form value does not reflect the newly added element until I make some change to the value in some text box that was originally bound. Why is this behavior and how can I get the value of the form if the dynamic addition of FormGroup is added?
My component and template code:
setControlsValues(){
this.form_band = this._fb.group({
name : [ 'test', [ Validators.required ] ],
bands : this._fb.array([
this._fb.group({
name : [ 'band 1', [ Validators.required] ],
score : 10
}),
this._fb.group({
name : [ 'band 2', [ Validators.required] ],
score : 8
})
])
});
}
addBand(){
this.form_band.controls.bands.controls.push(
this._fb.group({
name : [ '', Validators.required ],
score : 0
})
);
}
<form [formGroup]="form_band" validate="off">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" formControlName="name" autocomplete="off">
</div>
<div class="form-group" >
<h4>Bands</h4>
<div formArrayName="bands">
<div *ngFor="let band of form_band.controls.bands.controls; let i=index">
<div [formGroupName]="i">
<input type="text" class="form-control" formControlName="name">
<input type="text" class="form-control" formControlName="score">
</div>
</div>
</div>
<button type="button" class="btn" (click)="addBand()">Add band</button>
</div>
Run codesolvable
, .
addBand :
addBand(){
this.form_band.controls.bands.push(
this._fb.group({
name : [ '', Validators.required ],
score : 0
})
);
}