4

Enums in Angular templates

 3 years ago
source link: https://marco.dev/enums-angular
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

Author

Marco Molteni

Marco Molteni Blog


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK