Sohlae
Sohlae

Reputation: 766

Cannot Perform Two-way Binding in an Input Element Dynamically

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>

Result

    Label: Field 1
    Input: dolor

    Label: Field 2
    Input: dolor

    Label: Field 3
    Input: dolor

Upvotes: 1

Views: 375

Answers (2)

Patricio Vargas
Patricio Vargas

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

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41377

just use [(ngModel)]="field.value"

<input type="text" [(ngModel)]="field.value" />

Demo

Upvotes: 1

Related Questions