Angular 2表单和对象输入的数组

12 浏览
0 Comments

Angular 2表单和对象输入的数组

我正在构建一个发票应用程序来学习Angular2。我遇到的问题是如何构建包含3个输入的行项目组件,这些输入应该来自于并绑定到行项目数组中的一个对象。

在Angular 1中,我可以通过在输入的容器中添加ng-form指令来轻松实现这一点。这里的等效方法是什么呢?

这是我的代码:

HTML:

组件:

import { Component } from '@angular/core';
import { Invoice } from './invoice.model';
import { InvoiceLineItems } from './invoice-line-item.model';
@Component({
  selector: 'create-invoice',
  templateUrl: 'create-invoice/create-invoice.html'
})
export class CreateInvoiceComponent {
  model: Invoice = new Invoice(
    85,
    'CAD',
    null,
    [ // lineItems
      new InvoiceLineItems('Web development for BAnQ'),
      new InvoiceLineItems('Sept 1 to 3', 14, 910),
      new InvoiceLineItems('Sept 5 to 10', 34, 5293),
      new InvoiceLineItems('Sept 11 to 20', 24, 5293),
      new InvoiceLineItems('Sept 21 to 38', 11, 2493),
    ],
    13989,
    100,
    200,
    15000,
    '',
    null,
    '$'
  );
  getTotal(): number {
    return this.model.lineItems.reduce(
      (a, b): number => a + (isNaN(b.total) ? 0 : b.total),
      0);
  }
}

0
0 Comments

在这里的问题出现在输入名称中,在你的情况下,你使用的是name = "description",问题在于它总是会使用最后一个description来更新form.description.value。在你的情况下,你有一个description数组,你需要有一个form.description[i].value的数组。因此,解决方法是将description更改为唯一的name="description_{{i}}"。在ngFor中的每个输入都重复此操作。

为了解决这个问题,你可以这样做:

你可以在这里看到你的示例工作:

https://plnkr.co/edit/orldGCSYDUtlxzMFsVjL?p=preview

我的建议是始终使用ReactiveForms(模型驱动表单),也许我只会在小表单中使用FormsModule(模板驱动表单)。它更容易,对于处理数据数组更好。

希望解决你的问题。

你有一个使用响应式表单的示例吗?

谢谢你的回答,但我想改变一件事:[(ngModel)]="item.description"等。

有关此确切问题的更多信息,请参见此答案:

https://stackoverflow.com/a/47567879/1305026

0