处理以编程方式添加的表单元素

时间:2019-04-08 10:48:14

标签: angular

我正在研究允许用户动态添加新表单元素的组件。 https://stackblitz.com/edit/angular-h3tmfe和下面的代码。我有两个问题:

1)在添加新行之前,如何检查表单元素是否为空?

2)如何以编程方式访问表单元素中的值?

即如果{{invoiceForm.value | json}}的输出如下,我将如何访问“项目1”?即invoiceForm.itemRows(0).value或其他内容?

{
  "itemRows": [
    {
      "itemname": "item 1"
    },
    {
      "itemname": "item 2"
    }
  ]
}

app.component.html

<hello name="{{ name }}"></hello>
    <h3 class="page-header">Add Invoice</h3>
    <button type="button" (click)="addNewRow()" class="btn btn-primary">Add new Row</button><br>
    <form [formGroup]="invoiceForm">
      <div formArrayName="itemRows">
        <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>

    </form>
    <pre>{{invoiceForm.value | json}}</pre>

app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public invoiceForm: FormGroup;

  constructor(private _fb: FormBuilder) { }

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

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

  initItemRows() {
    return this._fb.group({
      itemname: ['']
    });
  }

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

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

2 个答案:

答案 0 :(得分:1)

您可以使用

访问Form数组值
this.formArr.value

要检查前一个字段是否为空

if (this.formArr.value[this.formArr.value.length-1].itemname !== ""){
  this.formArr.push(this.initItemRows());
} else {
  //display warning
}  

答案 1 :(得分:1)

这段代码可帮助您在添加/推送新行之前检查表单是否有效。

 addNewRow() {
    this.isClicked = true;
    const itemFormCtrl = this.invoiceForm.controls['itemRows'];
    if (itemFormCtrl.valid) {
      this.formArr.push(this.initItemRows());
      this.isClicked = false;
    }
  }

此处已更新StackBlitz