angular - 输入中的值在 Angular 2 中未绑定(bind)

标签 angular

我有一个循环遍历我所有 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/

相关文章:

angular - Rxjs 类型 Observable<Unknown> 不可分配给 Observable<void>

angular - 如何使用 Bootstrap 4 验证伪类 ( :valid, :invalid) with Angular 5 custom validations?

javascript - 使用 Angular 中的一个管道过滤表中的多列

node.js - 无法使用 fs.removeSync() 删除文件

html - 将菜单按钮转换为小屏幕的下拉菜单(Angular2)

Angular 4如何注入(inject)svg

Angular - 如何从现有数组启动 FormArray?

javascript - 尝试配置新的 webpack + angular2 项目时出现错误 TS2384 : Overload signatures must all be ambient or non-ambient

Angular 4 + PrimeNG 菜单 - 多个菜单项显示为事件状态

Angular 使用来自自定义管道的管道