我的问题很简单,如何在字符串数组中正确使用ng-model?
我尝试过这个:
Component.ts
toDos: string[] =["Todo1","Todo2","Todo3"];
Component.html
<div *ngFor="let item of toDos;let index = index">
<input [(ngModel)]="toDos[index]" placeholder="item" name="word{{index}}">
</div>
这不会产生任何错误,但是当尝试更改输入的内容时......它不起作用,它无法正常工作。
在下面的 StackBlitz 中,当您尝试编辑输入时会出现问题: StackBlitz
这应该如何完成?
非常感谢!
最佳答案
您可以使用长度等于 toDos 长度的辅助数组(count)
toDos: string[] =["Todo1","Todo2","Todo3"];
count:number[]=new Array(this.toDos.length); //An auxiliar array
click(){
this.toDos.push("Todo4");
//if change the length of array ToDo, we must change the array count
this.count=new Array(this.toDos.length)
}
<!--we iterate over count array-->
<div *ngFor="let item of count;let index = index">
<input [(ngModel)]="toDos[index]" placeholder="item" name="word{{index}}">
</div>
关于字符串数组中的 Angular 双向数据绑定(bind)无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376943/