How to use a typescript enum value in an Angular2 ngSwitch statement

后端 未结 9 696
深忆病人
深忆病人 2020-12-07 16:13

The Typescript enum seems a natural match with Angular2\'s ngSwitch directive. But when I try to use an enum in my component\'s template, I get \"Cannot read property \'xxx

9条回答
  •  一个人的身影
    2020-12-07 16:45

    You can create a custom decorator to add to your component to make it aware of enums.

    myenum.enum.ts:

    export enum MyEnum {
        FirstValue,
        SecondValue
    }
    

    myenumaware.decorator.ts

    import { MyEnum } from './myenum.enum';
    
    export function MyEnumAware(constructor: Function) {
        constructor.prototype.MyEnum = MyEnum;
    }
    

    enum-aware.component.ts

    import { Component } from '@angular2/core';
    import { MyEnum } from './myenum.enum';
    import { MyEnumAware } from './myenumaware.decorator';
    
    @Component({
      selector: 'enum-aware',
      template: `
        
    First Value
    Second Value
    `, }) @MyEnumAware // <---------------!!! export default class EnumAwareComponent { myEnumValue: MyEnum = MyEnum.FirstValue; toggleValue() { this.myEnumValue = this.myEnumValue === MyEnum.FirstValue ? MyEnum.SecondValue : MyEnum.FirstValue; } }

提交回复
热议问题