如何遍历数组并在 angular 2 的下拉选项中追加值?

How to iterate over array and append values in drop down options in angular 2?

我使用下面的代码遍历数组并在下拉选项中附加值。

searchcomponent.html:-

<div fxFlex.xs="100" class="ddlplatform" *ngFor="let dropdown of dropdownitems">
   <select class="ddloption">
      <option>{{dropdown}}</option>
       <option *ngFor="let item of dropdown">{{item}}</option>
   </select>
</div> 

searchcomponent.ts:-

 OnOptionChange(evt) {
   this.dropdownitems = ['Platform', 'Category'];
   this.Platform = ['Online', 'Offline'];
   this.Category = ['2W', '3W', '4W'];         
 }

有两个可用的下拉列表,即平台和类别。在平台下拉列表中,我想绑定在线和离线选项。如何在下拉列表中动态绑定选项?

您实际上可以在模板中使用 this 来帮助通过键引用组件的属性。通过利用此功能,您可以动态获取作为根 属性 的数组并在 *ngFor.

中使用它
<div fxFlex.xs="100" class="ddlplatform" *ngFor="let dropdown of dropdownitems">
  <select class="ddloption">
    <option>{{dropdown}}</option>
    <option *ngFor="let item of this[dropdown]" [value]="item">{{item}}</option>
  </select>
</div>

将您的选项和下拉菜单存储为一个复杂的对象而不是单独的数组可能会更明智。

OnOptionChange(evt) {
  this.dropdownItems = [ 
    { type: 'Platform', options: ['Online', 'Offline'] },
    { type: 'Category', options: ['2W', '3W', '4W'] }
  ];
}

HTML:

<div fxFlex.xs="100" class="ddlplatform" *ngFor="let dropdown of dropdownitems">
  <select class="ddloption">
    <option>{{dropdown.type}}</option>
    <option *ngFor="let item of dropdown.options" [value]="item">{{item}}</option>
  </select>
</div>