Reputation: 15679
I have a very simple mat-form-field, and it's acting funny. When I type in a value, it deselects after each letter I type:
<div *ngFor="let phone of user.phones; let i = index">
<mat-form-field>
<input matInput
matTooltip="Enter a phone number"
[(ngModel)]="user.phones[i]"
name="phone{{i}}"
placeholder="Primary phone">
</mat-form-field>
</div>
When I remove [(ngModel)]="user.phones[i]"
it works fine, but then it's not doing what I need it to do. user.phones[]
is just an array of strings. Am I missing something obvious?
export interface User {
name: string;
phones: string[];
}
console.log()
name: "John",
phones:Array(3)
0:"4-43235"
1:"654-65498"
2:"fs48j3w"
length:3
__proto__:Array(0)
Upvotes: 0
Views: 281
Reputation: 1947
You have to use trackBy
with the index for example. The reason is that you're binding to primitives in the array. I.e. string
;
You could use something like:
TEMPLATE
<div *ngFor="let phone of user.phones; let i = index; trackBy: trackByIndex">
<mat-form-field>
<input matInput matTooltip="Enter a phone number" [(ngModel)]="user.phones[i]" name="phone{{i}}" placeholder="Primary phone">
</mat-form-field>
</div>
COMPONENT
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 5';
user = {
phones: [
"4-43235",
"654-65498",
"654-123123"
]
}
trackByIndex(index: number, value: number) {
return index;
}
}
I've put a demo with the working code. Hope this helps: APP: https://angular-npqqa7.stackblitz.io CODE: https://stackblitz.com/edit/angular-npqqa7
Upvotes: 1