Search code examples
angularangular4-forms

What is wrong with this Angular form that makes it reset selected values in the UI unexpectedly?


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?


Solution

  • 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