Search code examples
angularngmodel

Angular ngModel inside ngForm with number array


I'm stuck on an issue since a while now and I can't figure out why this is happening.

I have a values: number[] = [10,10] variable in my component. When I'm modifying the first input, on the keyDown, it moves my cursor to the next input sometimes, or it loose the focus.

Here is an example Plunker : https://embed.plnkr.co/N4PO5CNvn0WJChgNIo59/

edit : the cursor move to the next input when the two values are the same. Example : 10, 10. If I will type any number, the focus will be transmitted to the next input. btw I'm using Chrome latest version


Solution

  • I encountered this issue, and luckily for you I remember how to resolve it !

    To resolve that, you need to define a custom trackBy function.

    Add this in your *ngFor :

    *ngFor="let val of values; let i = index; trackBy: trackByFn"
    

    In your component TS :

    trackByFn(index, item) {
      return index; // or item.id
    }
    

    Just tested it on plunkr, works like a charm !