0

For demonstration purposes, I've created this simplistic Angular app that lets users make a list of people: https://plnkr.co/edit/1RFGlXgHLwik02MvbhCz?p=preview

Template:

<form #peopleForm="ngForm">
<div *ngFor="let person of people">
   Name: <input type="text" name="name" placeholder="Name" [(ngModel)]="person.name">
 </div>
</form>

Component:

export class App {
  people = [
    {
      name: 'Bob',
    }, 
    {
      name: 'Alice',
    }
  ];

  constructor() { }

  addPerson() {
    this.people.push({name: ''});
  }
}

It has two bugs:

  • List items get reset in the UI when the "Add person" button is clicked
  • The last user's name is shown twice

I have the underlying JSON being printed to the page as well, and it looks correct, but the rest of the UI is wrong. Can anyone tell me what I'm doing wrong?

Update: For some reason, it works as expected when I remove the outer <form> tag. Anyone know why?

Stewart
  • 1,659
  • 4
  • 23
  • 35

2 Answers2

1

Update : ngModel wasnt working because you have not defined unique name for your input. Try this

<div *ngFor="let person of people; let i=index">
   Name: <input type="text" name="name{{i}}" placeholder="Name" [(ngModel)]="person.name" >
   Gender:
   <select name="gender{{i}}" [(ngModel)]="person.gender">
     <option value=""></option>
     <option value="m">Male</option>
     <option value="f">Female</option>
   </select>
 </div>

Updated plunker

JayDeeEss
  • 1,075
  • 9
  • 14
  • That is one-way binding. I need two-way binding. Look at the JSON and list of people underneath the form in your example. It doesn't update. – Stewart Oct 19 '17 at 12:54
-1
 <select name="gender" [(ngModel)]="person.gender">
 <option *ngFor="let value of person" [value]="value.gender">{{value.gender}}</option>

Try this, this will make drop-down dynamic.