Enums in Angular templates


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} 
  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.

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

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

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


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 = {})); 



## 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
Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).