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

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

    If using the 'typetable reference' approach (from @Carl G) and you're using multiple type tables you might want to consider this way :

    export default class AppComponent {
    
      // Store a reference to the enums (must be public for --AOT to work)
      public TT = { 
           CellType: CellType, 
           CatType: CatType, 
           DogType: DogType 
      };
    
      ...
    
      dog = DogType.GoldenRetriever; 
    

    Then access in your html file with

    {{ TT.DogType[dog] }}   => "GoldenRetriever"
    

    I favor this approach as it makes it clear you're referring to a typetable, and also avoids unnecessary pollution of your component file.

    You can also put a global TT somewhere and add enums to it as needed (if you want this you may as well make a service as shown by @VincentSels answer). If you have many many typetables this may become cumbersome.

    Also you always rename them in your declaration to get a shorter name.

提交回复
热议问题