Search code examples
angularinputbindingngmodel

ngFor generated input fields get different values - Angular 2


I have two (or perhaps more) input fields that are generated when I click on button. Currently, when I start to type something in any filed, it will also fill in other fields with that ngModel.

What i need is to make every row for it self so that when i click other button, it will get all input values and push them in array by rows so json should look something like this:

[{"name":"aaa", "data":"111"},{"name":"bbb", "data":"222"},{"name":"ccc", "data":"333"}]

Plunker is here: plunker


Solution

  • I think what you need is something like the following.

    @Component({
    selector: 'my-app',
    template: `
            <div *ngFor="let prop of properties; let i=index">
                <input type="text" placeholder="name" [(ngModel)]="prop.name"/>
                <input type="text" placeholder="data" [(ngModel)]="prop.data"/>
            </div>
        <button (click)="createRow()">Add row inputs</button>
        <button (click)="addRow()">show array input rows</button>
    `,
    })
    export class App {
        // property = { name:"", data: "" };
        properties = [];
    
        createRow(){
            this.properties.push({ name:"", data: "" });
        }
    
        addRow() {
            console.log(this.properties);
        }
    }
    

    The plunk didn't have a whole lot in it, so I don't know where you plan to go with this.

    Adding let i=index after the let part of the *ngFor gets you the index for the current item in the array. You can use that in your [(ngModel)] to tell Angular what to bind to from one row to the next.