Angular two way data binding in string array doesn't works correctly

Viewed 1974

My question is very simple, how to correctly use the ng-model in an array of strings?

I tried this:

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>

This does not generate any errors, but when trying to change the contents of the inputs ... it does not work, it does not work correctly.

In the following StackBlitz the problem is shown when you try to edit a input: StackBlitz

How should this be done?

Thank you very much!

3 Answers

You can use an auxiliar array (count) with the length equal length of toDos

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>

You can simply use the item as in the for loop it will hold the value in the item

Related