jus*_*web 4 angular2-forms angular
我正在构建一个开发票应用程序来学习Angular2.我遇到的问题是如何构建行项目组件,其中一行包含3个应该来自的输入并绑定到行项目数组中的对象.
在角度1中,我可以通过向ng-form输入的容器添加指令来轻松实现此目的.这里的等价物是什么?
这是我的代码:
HTML:
<form name="form" ng-submit="$ctrl.submit(form)" novalidate>
<!-- some more code -->
<ul class="list invoice-table__body">
<li *ngFor="let item of model.lineItems; let i = index">
<input
type="text"
name="description"
class="col-sm-8"
[(ngModel)]="item.description">
<input
type="number"
name="quantity"
class="col-sm-2"
[(ngModel)]="item.quantity">
<input
type="number"
name="total"
class="col-sm-2"
[(ngModel)]="item.total">
</li>
</ul>
<!-- some more code -->
</form>
Run Code Online (Sandbox Code Playgroud)
零件:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 15
这里的问题是在输入名称中,在你使用name ="description"的情况下,这里发生的事情总是要用最后的描述来更新form.description.value.在您的情况下,您有一系列描述,您需要有form.description [i] .value数组
所以修复是变更描述是唯一的.
NAME = "描述_ {{I}}"
对ngFor内的每个输入重复此操作.要解决此问题,您可以执行以下操作:
<ul class="list invoice-table__body">
<li *ngFor="let item of invoice.lineItems; let i = index">
<input
type="text"
name="description_{{i}}"
class="col-sm-8"
[(ngModel)]="invoice.lineItems[i].description">
<input
type="number"
name="quantity_{{i}}"
class="col-sm-2"
[(ngModel)]="invoice.lineItems[i].quantity">
<input
type="number"
name="total_{{i}}"
class="col-sm-2"
[(ngModel)]="invoice.lineItems[i].total">
</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
你可以看到你的例子在这里工作:https: //plnkr.co/edit/orldGCSYDUtlxzMFsVjL?p = preview
我的建议总是与ReactiveForms(模型驱动的表单)一起使用,也许我将使用FormsModule(模板驱动的表单)的唯一情况是小表单.它更容易,更适合做数据数组.
希望它能解决你的问题.
| 归档时间: |
|
| 查看次数: |
14450 次 |
| 最近记录: |