【问题标题】:Binding ngFor's Object's attribute name Dynamically动态绑定 ngFor 的 Object 的属性名
【发布时间】:2016-09-12 08:40:05
【问题描述】:

我的用例: 我正在使用 ngFor 将对象数组分配给 select 的选项,如下所示

<select>
 <option *ngFor="let item of data" [value]="item.key">{{item.value}}</option>
<select>

我的数据是

[
  {
    "key"   : "CHV",
    "value" : "Chivas"
  },
  {
    "key"   : "BLN",
    "value" : "Balentines"
  },
  {
    "key"   : "BDG",
    "value" : "Black Dog"
  }
]

相当直截了当,现在我想要绑定用户指定的 item.key 和 item.value,即他应该能够提及选项值和标签使用哪个。这是我尝试过但没有用的方法

<option *ngFor="let item of data; let itemlabel = optionlabel; let itemvalue = optionvalue" value="{{item.itemvalue}}">{{item.itemlabel}}</option>

optionvalue & optionlabel 是组件中的字符串,如下所示

optionvalue : string = 'key';
optionlabel : string = 'value';

所以现在当我交换它们时,我可以将键作为值,反之亦然。任何想法如何做到这一点

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以使用以下内容:

    <option *ngFor="let item of data" value="{{item[itemvalue]}}">
      {{item[optionlabel]}}
    </option>
    

    这样我们将利用您的组件中完成的配置。

    【讨论】:

    • 效果很好!谢谢,还有一件事,我现在正试图根据&lt;option *ngFor="let item of data" value="{{item[optionvalue]}}"&gt;{{getClubbedOption(item)}}&lt;/option&gt; 这样的用户来组合数据,但从未调用过该方法?知道为什么
    • 不客气! getClubbedOption 方法是什么?您的组件之一?
    • 基本上我想做的是让用户在显示选项时提及所有数据将被合并。是的getClubbedOption 是我的组件的一个方法,应该被调用。 getClubbedOption(item : any) : any{ console.log(item); console.log(this.optionlabel) return "opt"; }
    • 这里的问题是this关键字的使用,因为当你引用一个方法时,它变成了一个函数,你失去了它的执行上下文。我认为这个问题可以帮助你:stackoverflow.com/questions/37213908/…。读完题后的cmets,你会看到模板中使用了lookup方法...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多