2017-02-17 62 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

相關問題