ngModel在角度的for循环内不起作用

时间:2019-11-30 19:34:48

标签: angular ngfor

我正在开发一个应用程序,我试图在一个for循环内执行一个for循环,该for循环将有一个输入字段,当我编辑一个输入字段时,它将更新数组中的值,但我的问题是它会更新整个值而不是索引中的值, 这是数组

newSatas=[{"name":"","freeKG":"","CPMPK":""},{"name":"","freeKG":"","CPMPK":""}{"name":"","freeKG":"","CPMPK":""}]

这是for循环

<div *ngFor="let newSata of newSatas; let i=index; trackBy:trackByIndex;">
    <label>Delivery Name 
        <input type="text" [(ngModel)]="newSatas[i].name" name="name[{{i}}]" class="form-control" placeholder="Site Name">
    </label>
    <label>Price Per KiloMeter Per Kg
        <input type="text" [(ngModel)]="newSatas[i].CPMPK" name="CPMPK[{{i}}]" class="form-control" placeholder="Price Per KiloMeter Per Kg">
    </label>
    <label>Free KG
        <input type="text" [(ngModel)]="newSatas[i].freeKG" name="freeKG[{{i}}]" class="form-control" placeholder="Free KG">
    </label>
</div>

请问我如何只更新索引中的值而不是整个值

1 个答案:

答案 0 :(得分:0)

您如何创建阵列?可能是同一对象。

我相信您会这样做:

sata = {"name":"","freeKG":"","CPMPK":""}
newSatas = [];
for(let i = 0; i < 3; i++) newSatas.push(sata);

您将需要在每次迭代中创建一个新对象

newSatas = [];
for(let i = 0; i < 3; i++) newSatas.push({"name":"","freeKG":"","CPMPK":""});