Tanzeel
Tanzeel

Reputation: 4998

How to pass enum to values to a dropdown in template [Angular]

I've recently started with typescript. I've created a dropdown using select and option tags in the template.

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let mode of modes" [value]="mode">{{mode}}</option>
</select>

and in typescript I was having an array:

modes= ['Calendar Year', 'Year-to-date', 'Rolling Year', 'Custom'];

But my tech lead said that I've to use enum instead of array. Here's my code now:

import { Component, OnInit, ... } from '@angular/core';

export enum presetRange {
    CalendarYear,
    YearToDate,
    RollingYear,
    CustomRange
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  primaryMode;

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);    
  }
}

But the problem is that I don't know how to bind dropdown to an enum. I tried few things but I failed. Here's the stackblitz. Please correct me where I'm wrong.

Upvotes: 1

Views: 4048

Answers (2)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

Demo You can use Object.keys for this or you can write custom pipeline for this.

In component

  modes =[];
  enums = presetRange 

  constructor() {this.modes= Object.keys(this.enums).filter(Number) } 

in html

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let key of modes" [value]="key" >{{enums[key]}}</option>
</select>

Upvotes: 2

Barremian
Barremian

Reputation: 31115

String enums require a key and a value. And enums are used to create named constants, they don't produce a list. So you still need an array, but created from the values of the enum.

Controller

enum PresetRange {
  CalendarYear = 'Calendar Year',
  YearToDate = 'Year-to-date',
  RollingYear = 'Rolling Year',
  CustomRange = 'Custom'
}

@Component({
  selector: 'app-timeselector',
  templateUrl: './timeselector.component.html',
  styleUrls: ['./timeselector.component.css']
})
export class TimeselectorComponent implements OnInit {
  primaryMode: any;
  modesLabels = [                        // <-- you still need the array
    PresetRange.CalendarYear, 
    PresetRange.YearToDate, 
    PresetRange.RollingYear,
    PresetRange.CustomRange 
  ];

  constructor() { }

  ngOnInit() {
  }

  primaryModeChangeHandler(event) {
    console.log(this.primaryMode);    
  }
}

Template

<select [(ngModel)]="primaryMode" (ngModelChange)="primaryModeChangeHandler($event)">
  <option *ngFor="let label of modesLabels" [value]="label">{{label}}</option>
</select>

I've modified your Stackblitz

Upvotes: 3

Related Questions