RGS
RGS

Reputation: 5211

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

I have used below code to iterate over array and append values in drop down options.

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'];         
 }

There are two drop down lists available i.e., Platform and Category. In Platform drop down list I want to bind Online and Offline options. How to bind the options dynamically in the drop down list?

Upvotes: 0

Views: 2438

Answers (1)

Daniel Gimenez
Daniel Gimenez

Reputation: 20524

You can actually use this in templates to help refer to properties of your component by their key. By leveraging this feature you can dynamically get an array that's a root property and use it in *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>

It would probably be wiser to have your options and drop downs stored as a complex object instead of seperate arrays.

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>

Upvotes: 1

Related Questions