1

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
1
  • Also if you use two way databinding, as the bottom answers mentioned keep in mind that two way databinding is pretty rxpensive, through the fact that you have to listen bidirectional. It's by far more efficient to use input and output events separately and provide them from a smart component. Commented Sep 26, 2018 at 6:09

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.