Search code examples
enumsangularangular2-template

Pass enums in angular2 view templates


Can we use enums in an angular2 view template?

<div class="Dropdown" dropdownType="instrument"></div>

passes the string as input:

enum DropdownType {
    instrument,
    account,
    currency
}

@Component({
    selector: '[.Dropdown]',
})
export class Dropdown {

    @Input() public set dropdownType(value: any) {

        console.log(value);
    };
}

But how to pass an enum configuration? I want something like this in the template:

<div class="Dropdown" dropdownType="DropdownType.instrument"></div>

What would be the best practice?

Edited: Created an example:

import {bootstrap} from 'angular2/platform/browser';
import {Component, View, Input} from 'angular2/core';

export enum DropdownType {

    instrument = 0,
    account = 1,
    currency = 2
}

@Component({selector: '[.Dropdown]',})
@View({template: ''})
export class Dropdown {

    public dropdownTypes = DropdownType;

    @Input() public set dropdownType(value: any) {console.log(`-- dropdownType: ${value}`);};
    constructor() {console.log('-- Dropdown ready --');}
}

@Component({ selector: 'header' })
@View({ template: '<div class="Dropdown" dropdownType="dropdownTypes.instrument"> </div>', directives: [Dropdown] })
class Header {}

@Component({ selector: 'my-app' })
@View({ template: '<header></header>', directives: [Header] })
class Tester {}

bootstrap(Tester);

Solution

  • Create a property for your enum on the parent component to your component class and assign the enum to it, then reference that property in your template.

    export class Parent {
        public dropdownTypes = DropdownType;        
    }
    
    export class Dropdown {       
        @Input() public set dropdownType(value: any) {
            console.log(value);
        };
    }
    

    This allows you to enumerate the enum as expected in your template.

    <div class="Dropdown" [dropdownType]="dropdownTypes.instrument"></div>