1

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

2
  • There is no JSON in your question... Commented Mar 20, 2018 at 20:40
  • 1
    Anyway, your pushing a reference to an existing object into the array. Try this.properties.push({...this.property}) Commented Mar 20, 2018 at 20:42

1 Answer 1

3

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.

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

3 Comments

Yes, that is exaclty what I need ...I added function on second button: plnkr.co/edit/DSai2pfceIIBUxfSty0g?p=preview ...but for some reason, with your correction, I still don't catch values in array when it is showing in console.log
A small note: the template would be simpler with this syntax: [(ngModel)]="prop.name".
@ConnorsFan Indeed it would! Updated answer. Thanks.

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.