输入中的值未在 Angular 2 中绑定

Tyl*_*rry 6 angular

我有一个 *ngFor 循环遍历我所有的朋友。在 for I 中有一个输入框,用于存储朋友的姓名。我想在单击按钮时存储朋友的更新名称的值,但这并没有按预期工作:

@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) {}
}
Run Code Online (Sandbox Code Playgroud)

期望是使用包含名称的新值的朋友对象调用 save 方法。但它只是传递旧名称。

我觉得我在 Angular2 的工作方式中缺少一些基本的东西。

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

pix*_*its 11

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

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

或者使用以下命令设置双向数据绑定ngModel

<input type="text" [(ngModel)]="friend.name">
Run Code Online (Sandbox Code Playgroud)

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