Angular2-将ngModel绑定到属性的引用 [英] Angular2 - bind ngModel to a reference of a property

查看:90
本文介绍了Angular2-将ngModel绑定到属性的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a long list of user inputs, and would like to store these in an object instead of spelling them out in HTML. I want to bind these values to another object that stores the user/customer's data. Preferably using ngModel due to its simplicity and functionality.

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

Anyone knows how I can achieve this?

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

Example below (not working).

@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只能绑定到组件的属性.我也看不到没有辅助方法的情况下通过模板中的字符串文字来引用组件属性的方法:

That's not supported. ngModel can only bind to a property of the component. I also don't see a way to refer to a component property by a string literal from the template without helper methods:

这可能对您有用:

  <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>

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

hint for => RC.0 # should be replaced by let

这篇关于Angular2-将ngModel绑定到属性的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆