Angular2 - 将 ngModel 绑定到 属性 的引用

Angular2 - bind ngModel to a reference of a property

我有一长串用户输入,我想将它们存储在一个对象中,而不是在 HTML 中拼写出来。我想将这些值绑定到另一个存储 user/customer 数据的对象。由于其简单性和功能性,最好使用 ngModel。

有人知道我怎样才能做到这一点吗?

下面的示例(不起作用)。

@Component({
  template: `
    <div>
      <h2>NgModel Example</h2>
      <div *ngFor="let input of inputList">
        {{ input.label }} <input type="text" [(ngModel)]="input.bindTo">
      </div>
    </div>

    <p>This is not working: {{customerInfo.name}}, {{customerInfo.email}}</p>
  `,
  directives: [...]
})

export class AppComponent {
  inputList = [
    {
      label: "Enter your name",
      bindTo: this.customerInfo.name  // also tried 'customerInfo.name'
    },
    {
      label: "Enter your email",
      bindTo: this.customerInfo.email
    }
  ]  

  customerInfo = {
    name: 'test',
    email: ''
  }
}

不支持。 ngModel 只能绑定到一个 属性 的组件。我也没有看到在没有辅助方法的情况下通过模板中的字符串文字引用组件 属性 的方法:

这可能对你有用:

  <div *ngFor="#input of inputList">
    {{ input.label }} 
    <input type="text" 
        [ngModel]="getProp(input.bindTo)" 
        (ngModelChange)="setProp(input.bindTo, $event)">
  </div>
  inputList = [
    {
      label: "Enter your name",
      bindTo: "name"
    },
    {
      label: "Enter your email",
      bindTo: "email"
    }
  ];

  getProp(prop) {
    return this[prop];
  }

  setProp(prop, value) {
    this[prop] = value;
  }

  <div *ngFor="#input of inputList; #i = index">
    {{ input.label }} <input type="text" [(ngModel)]="inputList[i]">
  </div>

提示 for => RC.0 # 应替换为 let