Angular 4 Form FormArray Add a Button to add or delete a form input row

Here’s a shortened version of your code:

When you init your form, you can add one empty formgroup inside your formArray:

ngOnInit() {
  this.invoiceForm = this._fb.group({
    itemRows: this._fb.array([this.initItemRows()])
  });
}

get formArr() {
  return this.invoiceForm.get('itemRows') as FormArray;
}

Then the function:

initItemRows() {
  return this._fb.group({
    // list all your form controls here, which belongs to your form array
    itemname: ['']
  });
}

Here is the addNewRow and deleteRow functions:

addNewRow() {
  this.formArr.push(this.initItemRows());
}

deleteRow(index: number) {
  this.formArr.removeAt(index);
}

Your form should look like this:

<form [formGroup]="invoiceForm">
  <div formArrayName="itemRows">
    <div *ngFor="let itemrow of formArr.controls; let i=index"  [formGroupName]="i">
      <h4>Invoice Row #{{ i + 1 }}</h4>
      <div>
        <label>Item Name</label>
        <input formControlName="itemname">
      </div>
      <button type="button" (click)="deleteRow(i)" *ngIf="formArr.controls.length > 1" >
        Delete
      </button>
    </div>
  </div>
  <button type="button" (click)="addNewRow()">Add new Row</button>
</form>

Here’s a

DEMO

Leave a Comment