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

后端 未结 9 680
深忆病人
深忆病人 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:54

    Angular4 - Using Enum in HTML Template ngSwitch / ngSwitchCase

    Solution here: https://stackoverflow.com/a/42464835/802196

    credit: @snorkpete

    In your component, you have

    enum MyEnum{
      First,
      Second
    }
    

    Then in your component, you bring in the Enum type via a member 'MyEnum', and create another member for your enum variable 'myEnumVar' :

    export class MyComponent{
      MyEnum = MyEnum;
      myEnumVar:MyEnum = MyEnum.Second
      ...
    }
    

    You can now use myEnumVar and MyEnum in your .html template. Eg, Using Enums in ngSwitch:

    MyEnumVar {{myEnumVar}} is not handled.

提交回复
热议问题