Before proceeding, ask yourself 'Is this truly what I want to do?'
While it's easy to directly refer to enums in HTML, there are cleaner alternatives available that maintain type safety.
For example, if you adopt the method outlined in a different response, you might have defined TT in your component like so:
public TT =
{
// Enum options (Horizontal | Vertical)
FeatureBoxResponsiveLayout: FeatureBoxResponsiveLayout
}
To display a different layout in your HTML, you would use an *ngIf
for each layout type, and reference the enum directly in your component's HTML:
*ngIf="(featureBoxResponsiveService.layout | async) == TT.FeatureBoxResponsiveLayout.Horizontal"
This approach involves using a service to obtain the current layout, piping it asynchronously, and then comparing it to our enum value. It can be verbose, convoluted, and not very visually appealing. Additionally, it exposes the enum name, which could be excessively wordy.
An Alternative Approach to Maintain Type Safety in HTML
Alternatively, you can utilize the following method by creating a more readable function in your component's .ts file :
*ngIf="isResponsiveLayout('Horizontal')"
Cleaner and more concise! However, what happens if someone mistakenly types 'Horziontal'
? The whole point of using an enum in the HTML was to ensure type safety, right?
We can still achieve this using keyof and some TypeScript wizardry. Here is the function definition:
isResponsiveLayout(value: keyof typeof FeatureBoxResponsiveLayout)
{
return FeatureBoxResponsiveLayout[value] == this.featureBoxResponsiveService.layout.value;
}
Pay attention to the usage of
FeatureBoxResponsiveLayout[string]
, which converts the input string value into the numeric value of the enum.
If an invalid value is used, AOT compilation will trigger an error message:
Argument of type '"H4orizontal"' is not assignable to parameter of type '"Vertical" | "Horizontal"
Currently, VSCode may not highlight H4orizontal
in the HTML editor, but you will receive a warning during compilation (with --prod build or --aot switch). This behavior may be enhanced in a future update.