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%.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With