2

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 3

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

great example. once I start typing in, it takes only the first character. for example, if I want to make Todo1 as Todo12345 by typing in 2, then 3..., focus goes away after 2, have to click focus back to the box, then 3, etc. how to let it wait until I literally move cursor out of the input box?
@Jeb50, the idea is iterate over an array that you don't modify. see that I iterate over "count", not over toDos. If iterate over toDos you has the problem you described, else must not happen :(
2

You need to change the model to an array of objects, rather than an array of strings:

toDos: any[] =[
  { value : "Todo1" },
  { value : "Todo2" },
  { value : "Todo3" }];

Then change the ngModel to reference the property on the object:

<input [(ngModel)]="toDos[index].value" placeholder="item" name="word{{index}}">

You can see this working here:

https://stackblitz.com/edit/angular-poauvg?embed=1&file=src/app/app.component.ts

5 Comments

Thank you very much, but this only shows the problem, it does not solve it
your question is Angular two way data binding in string array and it's solved, I'm not sure your real question, could you describe more detail?
The problem occurs when you try to edit an input ... do the test and you will notice
@ChunbinLi Your latest comment does fix this issue
-2

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

1 Comment

If I do what you tell me, this error is generated: Cannot assign to a reference or variable! ( change this in the code [(ngModel)]="item" )

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.