我正在使用Angular5,并希望创建一个表单,用户可以在其中使用按钮插入新记录。每个记录中都有许多控件,应独立于其他记录进行更改。我已经做了很多次,但是现在我得到了奇怪的结果。
<form #newRequestForm="ngForm">
<a class="list-group-item" *ngFor="let detail of currentRequest.details; let index$ = index">
.
.
.
<ng-select [items]="products" [searchFn]="searchProduct" (change)="productChanged($event, detail)">
<ng-template ng-label-tmp let-item="item">
{{item.code}} - {{item.name1}}
</ng-template>
</ng-select>
<input class="form-control" name="productname1" type="text" [ngModel]="detail.product.name1" />
<input class="form-control" name="productname2" type="text" [ngModel]="detail.product.name2" />
<input class="form-control" name="productname3" type="text" [ngModel]="detail.product.name3" />
<input class="form-control" type="text" name="description" [(ngModel)]="detail.description" />
问题是由ng-select onchange productChanged
调用的方法设置了当前所选产品的产品名称。 (产品在erp中具有3个单独的名称字段。)发生这种情况时,表单中所有记录的所有3个名称字段都会更改为当前所选产品的名称字段。无论我使用哪种ng-select,一切都已改变。所有其他字段都单独工作,例如:description。
所以我想这个方法中有bug,但是它看起来像这样:
productChanged($event, detail) {
detail.product = $event;
console.log('-----------------------------------------');
this.currentRequest.details.forEach((d, i) => {
console.log(i, d.product !== null ? d.product.name1 : '');
});
}
是的,根据该记录的ng-select的最后选择,我尝试使用良好的旧console.log进行调试,并说每个detail.products的内容都是完美的。
无论我执行什么选择,输入控件仍将被重写。为什么?
答案 0 :(得分:1)
因为您没有按功能指定跟踪,所以Angular并不真正知道如何跟踪您的输入。
<a class="list-group-item" *ngFor="let detail of currentRequest.details; let index$ = index; trackBy: customTB">
customTB(index, item) { return index + '-' + item.product.name1; }