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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With