18

I have a simple list that binds two-way to a parameter hero in hero.component.ts.

Though when I start typing in the input field it loses focus and I have to click it again. What am I supposed to do in order to allow the user edit the input value without the input field loses target?

 <li *ngFor="let power of hero.powers; let i = index">
      <input [(ngModel)]="hero.powers[i]"/>
 </li>
iSebbeYT
  • 1,441
  • 2
  • 18
  • 29

3 Answers3

45

Using trackBy function of angular fixes the issue.

live example showing it

<hello name="{{ name }}"></hello>
<div>
   <li *ngFor="let power of hero.powers; let i = index; trackBy: trackByFn">
  <input [(ngModel)]="hero.powers[i]"/>
   </li>
</div>

component file

trackByFn(index, item) {
  return index;  
}
Franklin Pious
  • 3,670
  • 3
  • 26
  • 30
2

Did you try using trackBy:trackByFn in your ngFor, by using it prevent angular to recreate your DOM and it will keep track of changes

see this tutorial here

Reza
  • 18,865
  • 13
  • 88
  • 163
0

In html:

<div *ngFor="let a of a[]; let index = index; trackBy: trackByFn"> 

In TS:

trackByFn(index, item) {   return index; }
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103