Lijin Durairaj
Lijin Durairaj

Reputation: 5232

How to create a Reactive Form using only FormArray using Angular6?

I have a table which dynamically constructs rows as follows

<form [formGroup]='employeeForm'>
<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">name</th>
      <th scope="col">contact details</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor='let details of employeeDetails'>
      <th formControlName='name' scope="row">{{details.name}}</th>
      <td formControlName='employeeName'>{{details.contactDetails}}</td>
    </tr>
  </tbody>
</table>
</form>

now, how can i attach my dynamically created controls to the form? i tried this

 employeeForm: FormGroup
constructor(private formbuilder: FormBuilder) { }
 ngOnInit() {
this.employeeForm = this.formbuilder.array([])
  }

but it is giving me error stating, the formGroup cannot contain formArray

how can i add my formArray into the formGroup using reactive form approach?

Upvotes: 1

Views: 2811

Answers (1)

rrey
rrey

Reputation: 106

The sample that Akber Iqbal links to in their comment does what you want with FormBuilder. It may be easier to see how the types match up without FormBuilder though. A FormControl represents the actual form element (input, textarea, etc) in the html. FormGroup and FormArray are both containers that hold a mix of FormGroups, FormArrays, and/or FormControls. When you construct a FormGroup or FormArray, you pass in its initial child controls.

Below the parent FormGroup, employeeForm, contains a FormArray. I'll add two default child FormControls to the FormArray:

employeeForm: FormGroup;
nameArray: FormArray;

ngOnInit(){
    this.nameArray = new FormArray([
        new FormControl('name1'),
        new FormControl('name2')
    ]);

    this.employeeForm = new FormGroup({
        employeeNameArray: this.nameArray
    });
}

In the template you should be able to loop over the FormArray's children

<tr *ngFor="let employeeName of nameArray.controls; let i=index">
    <td>Name: <input type="text" [formControlName]="i"></td>
</tr>

If you want to have multiple form elements per employee (one for name and one for address for instance) you will probably want to have one more layer of nesting where the FormArray's immediate children are FormGroups that then each contain a name FormControl and an address FormControl.

Upvotes: 3

Related Questions