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

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

    Start by considering 'Do I really want to do this?'

    I have no problem referring to enums directly in HTML, but in some cases there are cleaner alternatives that don't lose type-safe-ness. For instance if you choose the approach shown in my other answer, you may have declared TT in your component something like this:

    public TT = 
    {
        // Enum defines (Horizontal | Vertical)
        FeatureBoxResponsiveLayout: FeatureBoxResponsiveLayout   
    }
    

    To show a different layout in your HTML, you'd have an *ngIf for each layout type, and you could refer directly to the enum in your component's HTML:

    *ngIf="(featureBoxResponsiveService.layout | async) == TT.FeatureBoxResponsiveLayout.Horizontal"
    

    This example uses a service to get the current layout, runs it through the async pipe and then compares it to our enum value. It's pretty verbose, convoluted and not much fun to look at. It also exposes the name of the enum, which itself may be overly verbose.

    Alternative, that retains type safety from the HTML

    Alternatively you can do the following, and declare a more readable function in your component's .ts file :

    *ngIf="isResponsiveLayout('Horizontal')"
    

    Much cleaner! But what if someone types in 'Horziontal' by mistake? The whole reason you wanted to use an enum in the HTML was to be typesafe right?

    We can still achieve that with keyof and some typescript magic. This is the definition of the function:

    isResponsiveLayout(value: keyof typeof FeatureBoxResponsiveLayout)
    {
        return FeatureBoxResponsiveLayout[value] == this.featureBoxResponsiveService.layout.value;
    }
    

    Note the usage of FeatureBoxResponsiveLayout[string] which converts the string value passed in to the numeric value of the enum.

    This will give an error message with an AOT compilation if you use an invalid value.

    Argument of type '"H4orizontal"' is not assignable to parameter of type '"Vertical" | "Horizontal"

    Currently VSCode isn't smart enough to underline H4orizontal in the HTML editor, but you'll get the warning at compile time (with --prod build or --aot switch). This also may be improved upon in a future update.

提交回复
热议问题