Reputation: 766
I have the following object in my typescript class:
export class XComponent {
fields: [{ }];
constructor() {
this.fields = [
{
id: 'Id1',
name: 'Field 1',
value: 'lorem'
},
{
id: 'Id2',
name: 'Field 2',
value: 'ipsum'
},
{
id: 'Id3',
name: 'Field 3',
value: 'dolor'
},];
}
}
When I try to bind the value dynamically in an input element it binds the last value which is dolor.
<div *ngFor="let field of fields; index as i">
<label>{{ field.name }}</label> <!-- This one is rendered correctly. -->
<input type="text" [(ngModel)]="fields[i].value" />
</div>
Label: Field 1
Input: dolor
Label: Field 2
Input: dolor
Label: Field 3
Input: dolor
Upvotes: 1
Views: 375
Reputation: 5522
You don't need to pass the index anymore. You are looping thought an array of objects with the *ngFor
<div *ngFor="let field of fields;">
<label>{{ field.name }}</label> <!-- This one is rendered correctly. -->
<input type="text" [(ngModel)]="field.value" />
</div>
Here's a working demo https://stackblitz.com/edit/angular-fre6m5
Upvotes: 3
Reputation: 41377
just use [(ngModel)]="field.value"
<input type="text" [(ngModel)]="field.value" />
Upvotes: 1