Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value within input not binding in Angular 2

Tags:

angular

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

like image 250
Tyler Murry Avatar asked Feb 17 '17 04:02

Tyler Murry


1 Answers

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

like image 65
pixelbits Avatar answered Nov 03 '22 00:11

pixelbits