我有一个循环遍历我所有 friend 的 *ngFor。在 for 中,我有一个输入框,用于存储 friend 的姓名。单击按钮时,我想存储 friend 的更新名称的值,但这没有按预期工作:
@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) {}
}
期望使用包含名称新值的 friend 对象调用 save 方法。但它只是通过旧名称。
我觉得我在 Angular2 的工作方式上缺少一些基本的东西。
Plunkr : http://plnkr.co/edit/blYzEW0JufOcPwIwzoWQ?p=preview
最佳答案
您需要处理更改事件 - 当它更改时分配 friend.name
:
<input type="text" (change)='friend.name=$event.target.value' [value]="friend.name">
或者使用
ngModel
设置双向数据绑定(bind):<input type="text" [(ngModel)]="friend.name">
Demp Plnkr:http://plnkr.co/edit/49tWBSyZAIToreQKyOh6?p=preview
关于angular - 输入中的值在 Angular 2 中未绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289665/