Strange behaviour with ngModel and looping over the array

🐞 bug report


I’ve created simple input using ngFor and ngModel connected to array element.

 data = [
*ngFor="let el of data;let i = index"

After focusing first input and typing one character:

  • input value changes
  • focus is lost and moves to next input
  • the following input value is set to previous input value
  • after typing another character whole text is copied to next input and it gain focus

Can anyone explain this behaviour? It looks like the bug

🔬 Minimal Reproduction


Adding trackBy function to *ngFor (using array index) solves the issue

🌍 Your Environment

Angular Version:

Tested with both angular 10 and 11

1 possible answer(s) on “Strange behaviour with ngModel and looping over the array

  1. You need to use an array of objects, and bind to a property of those objects, or to use trackBy and track by index: your ngModel replaces a string in the array by another string, thus forcing Angular to delete the DOM node which has the focus and recreate it, causing the focus to be lost.

    Similar stackoverflow questions/answers: