Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Material - Why is my input deselected?

I have a weird problem.

I am using Angular CLI and I have added Material 2 to it. I created some inputs with ngfor and bound them to ngmodel. Everything is working fine.

But whenever I type something, the input becomes deselected.

This is the HTML code of the component:

<md-input-container class="treatments" *ngFor="let t of treatment; let i = index">
    <input mdInput placeholder="treatment {{ i + 1 }}" 
      value="{{ t[i] }}" name="treatment_{{ i + 1 }}" [(ngModel)]="treatment[i]">
</md-input-container>

When I remove the ngmodel, it does work 100%.

like image 475
TheSnake620 Avatar asked Jan 19 '26 09:01

TheSnake620


1 Answers

You are iterating over an Array of primitive type, and thus they are compared by value. When you change a treatment (i.e t), all values are destroyed and new ones created, which causes the field to loose focus. This can be solved by using trackBy, which tracks the treatments by the index and only destroys and recreates the treatment you are modifying.

So add trackBy:

<md-input-container class="treatments" *ngFor="let t of treatment; 
    let i = index; trackBy:trackByFn">

and in TS add the function:

trackByFn(index, treatment) {
  return index;
}
like image 132
AT82 Avatar answered Jan 20 '26 23:01

AT82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!