简体   繁体   中英

Display the enum type in a select box with angular 5 and typescript?

I have an angular 5 application. I have declared an enum constant named DateRange.

export enum DateRange {
  TODAY = 'Today',
  THIS_WEEK = 'This Week',
  THIS_MONTH = 'This Month',
  THIS_YEAR = 'This Year'
}

I would like to display this enum in my select box in my components html. Any idea how can I achieve it?

I would expect it as follows

<select> 
  <option value="TODAY"> Today </option>
  <option value="THIS_WEEK"> This Week</option>
  <option value="THIS_MONTH">This Month </option>
  <option value="THIS_YEAR"> This Year </option>
</select>

Define the following in your html:

<select> 
   <option *ngFor="let range of Object.keys(ranges)" [ngValue]="range">{{ranges[range]}}</option>
</select>

Define the following in your component:

ranges= DateRange;

You can convert enum like JS object.

Object.values(DateRange); // [ 'Today', 'This Week', 'This Month', 'This Year']
Object.keys(DateRange); // [ 'TODAY', 'THIS_WEEK', 'THIS_MONTH', 'THIS_YEAR' ]

now you can show it use *ngFor

you can loop throught the keys of the enum and take them as value of your dropdown like this:

<select> 
  <option [value]="key" *ngFor="let key of getKeys(DateRange)">{{ DateRange[key] }}</option>
</select>

and i the component.ts you have to add the function getKeys like this:

getKeys(obj: any) { return Object.keys(obj); }

for sure the enum must also be a part of this component...

Define the following in your component:

const dateRanges = Object.keys(DateRange).map(key => DateRange[key]);
const selectedDateRange: DateRange = dateRanges[0];

Then use it in your template as follows:

<mat-form-field> 
    <mat-select placeholder="Date Range" [(value)]="selectedDateRange">
        <mat-option *ngFor="let dateRange of dateRanges" [value]="dateRange">
            {{ dateRange }}
        </mat-option>
    </mat-select>
</mat-form-field> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM