Search code examples
angularfocusngfor

Why does ngFor break focus on input when function is used to return array of objects


Focus blocks input (you cant type anything) while iterate using *ngfor over array of objects returned by function. However the same works when array of objects is inside the template. What's the problem?

enter image description here

template

<!-- does not work -->
<div *ngFor="let d of testValues()">
  <input (focus)="testFocus($event)" type="text" />
</div>


<!-- works -->
<div *ngFor="let d of [{ a: 0 }, { a: 1 }]">
  <input (focus)="testFocus($event)" type="text" />
</div>

component

  testValues() {
    return [{ a: 0 }, { a: 1 }];
  }

  testFocus($event: FocusEvent) {
    console.log('focus ', $event);
  }

Stackblitz


Solution

  • Wild guess, but I'd say that's because the focus event triggers a ChangeDetection.

    With that change detection, your method testValues() will return a new set of values. So the input you clicked has been replaced with a new one and is no longer there.


    Edit: Confirmed this is it, the following code fixes it :

      private values =  [{ a: 0 }, { a: 1 }];
    
    
      testValues() {
        return this.values;
      }
    

    Here, when the change detection happens, the value returned by the method is the same instance of your array, so the inputs stay the same.