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

后端 未结 1 1735
耶瑟儿~
耶瑟儿~ 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:

    Invoice Row #{{ i + 1 }}

    Here's a

    DEMO

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