Start by thinking, βDo I really want to do this?β
I have no problem with enumeration links directly in HTML, but in some cases there are cleaner alternatives that do not lose type safety. For example, if you choose the approach shown in my other answer, you might have declared TT in your component something like this:
public TT = {
To show a different layout in your HTML, you must have *ngIf for each layout type, and you can directly access enum in your HTML component:
*ngIf="(featureBoxResponsiveService.layout | async) == TT.FeatureBoxResponsiveLayout.Horizontal"
In this example, the service is used to get the current layout, it is started via the asynchronous channel and then compared with our enumeration value. It is rather verbose, confusing and not very interesting to watch. It also exposes the name enum, which in itself may be too verbose.
An alternative that maintains type safety from HTML
Alternatively, you can do the following and declare a more readable function in your .ts component file:
*ngIf="isResponsiveLayout('Horizontal')"
Much cleaner! But what if someone 'Horziontal' is mistaken? The whole reason you wanted to use enum in HTML was to be safe, right?
We can still achieve this with keyof and some typewriting magic. This is the function definition:
isResponsiveLayout(value: keyof typeof FeatureBoxResponsiveLayout) { return FeatureBoxResponsiveLayout[value] == this.featureBoxResponsiveService.layout.value; }
Note the use of FeatureBoxResponsiveLayout[string] which converts the passed string value to a numeric enumeration value.
This will give an error message with AOT compilation if you use an invalid value.
An argument of type "H4orizontal" cannot be assigned to a parameter of type "Vertical" | "Horizontal"
VSCode is currently not smart enough to emphasize H4orizontal in the HTML editor, but you will get a warning at compile time (using --prod build or --aot switch). It may also be improved in a future update.