20

I have an *ngFor that loops through all my Friends. Within the for I have an input box that stores the name of the friend. I would like to store the value of the update name of the friend when I click a button, but this is not working as expected:

@Component({
  selector: 'my-app',
  template: `
  <div *ngFor="let friend of friends">
    <input type="text" [value]="friend.name">
    <button (click)="save(friend)" type="submit">save</button>
  </div>`,
  providers: []
})
export class App {
  friends: Friend[] = new Array(new Friend("Alice"), new Friend("Bob"));

  save(friend: Friend) {
    console.log(friend.name);
  }
}

export class Friend {
  constructor(public name: string) {}
}

The expectation is that the save method would be called with a friend object that contains the new value for the name. But it's just passing the old name.

I feel like I'm missing something fundamental with the way Angular2 works.

Plunkr: http://plnkr.co/edit/blYzEW0JufOcPwIwzoWQ?p=preview

1
  • its passing the old name because you're passing the old name into the save method. Commented Feb 17, 2017 at 4:53

1 Answer 1

48

You need to handle the change event - when it changes assign friend.name:

<input type="text" (change)='friend.name=$event.target.value' [value]="friend.name">

Or setup two-way data binding with ngModel:

<input type="text" [(ngModel)]="friend.name">

Demp Plnkr: http://plnkr.co/edit/49tWBSyZAIToreQKyOh6?p=preview

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.