FormArray添加按钮以添加或删除表单输入行

FormArray添加按钮以添加或删除表单输入行

本文介绍了Angular 4 Form FormArray添加按钮以添加或删除表单输入行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 4.0.2构建一个应用程序。我怎样才能添加一个按钮到表单添加一个新的输入行和删除按钮删除特定的行?我的意思是我想要一个像这样的表单。我希望我的表单看起来像这样:





add-invoice.component.html

这是我的代码:

 < h3 class =page-header>添加发票< / h3> 
< form [formGroup] =invoiceForm>
< div formArrayName =itemRows>
< div * ngFor =let itemrow of itemRows.controls; let i = index[formGroupName] =i>
< h4>发票行#{{i + 1}}< / h4>
< div class =form-group>
< label>项目名称< / label>
< input formControlName =itemnameclass =form-control>
< / div>
< div class =form-group>
< label>数量< / label>
< input formControlName =itemqtyclass =form-control>
< / div>
< div class =form-group>
< label>单位成本< / label>
< input formControlName =itemrateclass =form-control>
< / div>
< div class =form-group>
< label>税务< / label>
< input formControlName =itemtaxclass =form-control>
< / div>
< div class =form-group>
< label>金额< / label>
< input formControlName =amountclass =form-control>
< / div>
< button> ngIf =i> 1(click)=deleteRow(i)class =btn btn-danger>删除按钮< /按钮>
< / div>
< / div>
< button type =button(click)=addNewRow()class =btn btn-primary>添加新行< / button>
< / form>
< p> {{invoiceForm.value | JSON}}< / p为H.

这是我的add-invoice.component.ts代码

 从'@ angular / core'导入{Component,OnInit}; 
从'@ angular / forms'导入{FormBuilder,FormControl,FormArray,FormGroup};

@Component({
选择器:'app-add-invoice',
templateUrl:'./add-invoice.component.html',
styleUrls: ['./add-invoice.component.css']
})

导出类AddInvoiceComponent实现OnInit {
invoiceForm:FormGroup;

构造函数(
private _fb:FormBuilder
){
this.createForm();


createForm(){
this.invoiceForm = this._fb.group({
itemRows:this._fb.array([])
});
this.invoiceForm.setControl('itemRows',this._fb.array([]));
}

获取itemRows():FormArray {
返回this.invoiceForm.get('itemRows')FormArray;
}

addNewRow(){
this.itemRows.push(this._fb.group(itemrow));


ngOnInit(){

}
}


解决方案

这是您的代码的缩短版本: 当您初始化表单时,添加你的formArray中有一个空的formgroup:


$ b

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

然后函数:

initItemRows(){
return this._fb.group({
//列出您所有的表单控件,属于到你的表单数组
itemname:['']
});

$ / code>

以下是 addNewRow deleteRow 函数:
$ b

  addNewRow (){
//控件引用你的formarray
const控件=< FormArray> this.invoiceForm.controls ['itemRows'];
//添加新的表单组
control.push(this.initItemRows());


deleteRow(index:number){
//控件引用您的formarray
const控件=< FormArray> this.invoiceForm.controls ['itemRows ];
//删除所选行
control.removeAt(index);

$ / code>

您的表单应该如下所示:




$ b

 < form [formGroup] =invoiceForm> 
< div formArrayName =itemRows>
< div * ngFor =let itemrow of invoiceForm.controls.itemRows.controls; let i = index[formGroupName] =i>
< h4>发票行#{{i + 1}}< / h4>
< div class =form-group>
< label>项目名称< / label>
< input formControlName =itemnameclass =form-control>
< / div>
< button * ngIf =invoiceForm.controls.itemRows.controls.length> 1(click)=deleteRow(i)class =btn btn-danger>删除按钮< /按钮>
< / div>
< / div>
< button type =button(click)=addNewRow()class =btn btn-primary>添加新行< / button>
< / form>

这里有一个


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 form something like this. I want my form to look something like this:

.

Here is my code:

add-invoice.component.html

    <h3 class="page-header">Add Invoice</h3>
    <form [formGroup]="invoiceForm">
      <div formArrayName="itemRows">
        <div *ngFor="let itemrow of itemRows.controls; let i=index" [formGroupName]="i">
          <h4>Invoice Row #{{ i + 1 }}</h4>
          <div class="form-group">
            <label>Item Name</label>
            <input formControlName="itemname" class="form-control">
          </div>
          <div class="form-group">
            <label>Quantity</label>
            <input formControlName="itemqty" class="form-control">
          </div>
          <div class="form-group">
             <label>Unit Cost</label>
             <input formControlName="itemrate" class="form-control">
          </div>
          <div class="form-group">
            <label>Tax</label>
            <input formControlName="itemtax" class="form-control">
          </div>
          <div class="form-group">
            <label>Amount</label>
            <input formControlName="amount" class="form-control">
          </div>
          <button *ngIf="i > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete Button</button>
        </div>
      </div>
      <button type="button" (click)="addNewRow()" class="btn btn-primary">Add new Row</button>
    </form>
    <p>{{invoiceForm.value | json}}</p>

Here is my code for add-invoice.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormArray, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-add-invoice',
  templateUrl: './add-invoice.component.html',
  styleUrls: ['./add-invoice.component.css']
})

export class AddInvoiceComponent implements OnInit {
  invoiceForm: FormGroup;

  constructor(
    private _fb: FormBuilder
  ) {
    this.createForm();
  }

  createForm(){
    this.invoiceForm = this._fb.group({
      itemRows: this._fb.array([])
    });
    this.invoiceForm.setControl('itemRows', this._fb.array([]));
  }

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

  addNewRow(){
    this.itemRows.push(this._fb.group(itemrow));
  }

  ngOnInit(){

  }
}
解决方案

Here's a shortened version of your code:

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

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

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() {
    // control refers to your formarray
    const control = <FormArray>this.invoiceForm.controls['itemRows'];
    // add new formgroup
    control.push(this.initItemRows());
}

deleteRow(index: number) {
    // control refers to your formarray
    const control = <FormArray>this.invoiceForm.controls['itemRows'];
    // remove the chosen row
    control.removeAt(index);
}

Your form should look like this:

<form [formGroup]="invoiceForm">
  <div formArrayName="itemRows">
    <!-- Check the correct way to iterate your form array -->
    <div *ngFor="let itemrow of invoiceForm.controls.itemRows.controls; let i=index"  [formGroupName]="i">
      <h4>Invoice Row #{{ i + 1 }}</h4>
      <div class="form-group">
        <label>Item Name</label>
        <input formControlName="itemname" class="form-control">
      </div>
      <button *ngIf="invoiceForm.controls.itemRows.controls.length > 1" (click)="deleteRow(i)" class="btn btn-danger">Delete Button</button>
    </div>
  </div>
  <button type="button" (click)="addNewRow()" class="btn btn-primary">Add new Row</button>
</form>

Here's a

DEMO

这篇关于Angular 4 Form FormArray添加按钮以添加或删除表单输入行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:34