2017-02-17 59 views
1

我有一个* ngFor循环遍历所有的朋友。在我有一个输入框存储的朋友的名字。我想用来存储好友的更新name的值当我点击一个按钮,但预计这不工作:输入中的值不在Angular 2中绑定

@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) {} 
} 

的期望是,保存方法将与朋友的对象被称为是包含名称的新值。但它只是传递旧名称。

我觉得我错过了Angular2工作方式的根本。

Plunkrhttp://plnkr.co/edit/blYzEW0JufOcPwIwzoWQ?p=preview

+0

它传递旧名称,因为您将旧名称传入保存方法。 – Kilmazing

回答

1

您需要办理变更事件 - 当它改变分配friend.name

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

或设置双向数据与ngModel绑定:

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

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