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

后端 未结 1 1720
耶瑟儿~
耶瑟儿~ 2020-11-27 14:14

I am building an app using Angular 4.0.2. How can I add a button to a form to add a new row of input and a delete button for a particular row to delete? I mean that I want a

相关标签:
1条回答
  • 2020-11-27 14:35

    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

    0 讨论(0)
提交回复
热议问题