Enums in Angular templates

Updated:

The TypeScript enum can be used directly in your class, but it has to be assigned to a local variable to be used in the template.

Declaration example:

import { Component } from '@angular/core'; 
 
enum LanguageType {Java = 1, 'JavaScript' = 2, "TypeScript" = 3} 
 
@Component({ 
  selector: 'my-app', 
  templateUrl: './app.component.html', 
  styleUrls: [ './app.component.css' ] 
}) 
export class AppComponent  { 
  languageTypeDeclaredInComponent = LanguageType; 
 
constructor() { 
  // this works 
  console.log("Language Java", LanguageType.Java); 
  // this works 
  console.log("Language JavaScript", this.languageTypeDeclaredInComponent.JavaScript) 
  } 
} 

The template can work only with your local variable and not the enum self.
The template can access only objects exposed by the controller or the component.

<p> 
OK, Enum for Java: <i>languageTypeDeclaredInComponent.Java</i>  
</p> 
<p> 
OK, Validity: <i>languageTypeDeclaredInComponent.Java === 1</i> 
</p> 
<p> 
KO, This doesn't work : <i>LanguageType.Java</i> 
</p> 

If you use directly the enum in the template the browser will show the following exception:

ERROR Error: Cannot read property [...] of undefined

Transpilation

enum doesn't exist in JavaScript. During the transpilation it's converted in an array:

enum ExampleType { Java = 1, 'JavaScript' = 2, TypeScript = 3 }; 
var ExampleType; 
(function (ExampleType) { 
    ExampleType[ExampleType["Java"] = 1] = "Java"; 
    ExampleType[ExampleType["JavaScript"] = 2] = "JavaScript"; 
    ExampleType[ExampleType["TypeScript"] = 3] = "TypeScript"; 
})(ExampleType || (ExampleType = {})); 
; 

Example

https://angularenum.stackblitz.io

## References

TypeScript reference

Angular - GitHub: Usage of enums in templates not possible?

Angular - GitHub: Allow constants, enums, functions to be used in templates


You could be interested in

Right click context menu with Angular

Right click custom menu inside dynamic lists with Angular Material
2020-05-31

Breadcrumb in an Angular application

Show a hierarchical and dynamic breadcrumb in an Angular application configured in the route definition
Olivier Canzillon / 2021-01-24
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).