如何使用输入数组构建Angular 2反应形式

时间:2016-11-13 15:51:38

标签: angular angular2-formbuilder

我正在构建自己的发票应用以学习Angular 2.我使用formBuilder创建了我的模型。我的模型包含一系列输入(发票的行项目),一旦在我的模板中映射,我就会收到错误。 (我按照这个例子:https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2)。

这是错误,控制器和模板:

错误:

Error in create-invoice/create-invoice.html:109:19 caused by: Cannot find control with name: 'i'

控制器:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, Validators, FormGroup, FormArray } from '@angular/forms';
import { Subscription } from 'rxjs/Rx';

import { Client } from '../clients/client.model';
import { Invoice, InvoiceLineItems } from '../invoices/invoice.model';
import { CreateInvoiceService } from './create-invoice.service';

@Component({
  selector: 'create-invoice',
  templateUrl: 'create-invoice/create-invoice.html',
  providers: [CreateInvoiceService]
})
export class CreateInvoiceComponent implements OnInit, OnDestroy {
  private FLOAT_REGEX: string = '^[0-9]+([,.][0-9]+)?$';
  public model: FormGroup;

  constructor(
    private _router: Router,
    private _route: ActivatedRoute,
    private _createInvoiceService: CreateInvoiceService,
    private _formBuilder: FormBuilder
  ) {}

  /* more code here */

  ngOnInit() {
    this.clients = this._route.snapshot.data['clients'].data;
    this.model = this._formBuilder.group({
      rate: [85, [Validators.required, Validators.pattern(this.FLOAT_REGEX)]],
      currency: ['CAD', [Validators.required, Validators.pattern(this.FLOAT_REGEX)]],
      client: [null, Validators.required],
      lineItems: this._formBuilder.array([
        this.initLineItem(),
      ]),
      notes: [null],
      discount: [null],
      discountUnit: ['$'],
    });
  }

  ngOnDestroy() {
    this.postInvoiceSubscription.unsubscribe();
  }

  initLineItem(): FormGroup {
    return this._formBuilder.group({
      description: [null],
      quantity: [null, Validators.pattern(this.FLOAT_REGEX)],
      total: [null, Validators.pattern(this.FLOAT_REGEX)]
    });
  }

  addAnItem() {
    const control = this.model.controls['lineItems'].value;
    control.push(this.initLineItem());
  }

  /* more code here */
}

模板(引发错误的区域):

<div class="invoice-table__body">
  <ul class="list invoice-table__list-items">
    <li *ngFor="let item of model.controls.lineItems.controls; let i = index">
      <div formGroupName="i">
        <input
          type="text"
          formControlName="description"
          class="col-sm-8"
          placeholder="Item description...">

        <input
          type="number"
          class="col-sm-2"
          formControlName="quantity">

        <p
          *ngIf="item.quantity"
          class="col-sm-2 invoice-table__line-item-total">
          {{ calculateLineItemTotal(item, item.quantity) | currency:'USD':true }}
        </p>
      </div>
    </li>
  </ul>

  <button
    type="button"
    class="btn btn--primary invoice-table__add-row-btn"
    (click)="addAnItem()">
    Add an item
  </button>
</div>

1 个答案:

答案 0 :(得分:1)

好的,找出原因。我没有注意到包含formArrayName的元素的*ngFor属性。该属性的值应该是包含formBuilder.array的属性的名称。就我而言formArrayName="lineItems"

此外,formGroupName属性应该用方括号括起来:[formGroupName]="i"