I want to create formArray inside FormGroup. formArray have multiple formGroup and FormGroup is created but i'm enable to bind data in html if i'm write something in input tag which is 0 index but data reflect on last FormGroup.
HTML:
<form [formGroup]="form">
<table>
<thead>
<tr>
<th>City</th>
<th>Employee id</th>
</tr>
</thead>
<tbody formArrayName="myNewArray">
<tr *ngFor="let controls of form.get('myNewArray').controls; let i = index">
<div [formGroupName]="i">
<td>
<mat-form-field>
<input matInput class="size-input" formControlName="first">
</mat-form-field>
</td>
<td>
<mat-form-field>
<input matInput class="size-input" formControlName="second">
</mat-form-field>
</td>
</div>
</tr>
</tbody>
<pre>{{form.value | json}}</pre>
</table>
</form>
TS:
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormGroup, FormBuilder, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
myNewArray: this.fb.array([])
});
}
ngOnInit(): void {
const formGroup = { };
let abc = ['first', 'second'];
abc.forEach(formControl => {
formGroup[formControl] = new FormControl("", Validators.required);
});
for (let value in abc) {
let formGroupArray = <FormArray>this.form.controls.myNewArray;
formGroupArray.push(this.setUsersFormArray(formGroup));
}
}
private setUsersFormArray (formGroup) {
return this.fb.group(formGroup)
}
}
Also check on link:- https://stackblitz.com/edit/angular-ptbvgd?file=src/app/app.component.html