How can I use Enums in the Angular 8 template?
component.ts
import { Component } from '@angular/core'; import { SomeEnum } from './global'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = SomeEnum.someValue; }
component.html
<span *ngIf="name === SomeEnum.someValue">This has some value</value>
This currently doesn't work, since the template has no reference to SomeEnum
. How can I solve it?
ERROR Error: Cannot read property 'someValue' of undefined
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. 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.
Enums can be used in your Angular templates.
Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
in the TS
import { SomeEnum } from 'path-to-file'; public get SomeEnum() { return SomeEnum; }
in the HTML use
*ngIf="SomeEnum.someValue === 'abc'"
EDIT: Time goes by and we learn more as a developer, the approach I'm using right now doesn't use the get
method. Both solutions work, just choose the one you like the most.
in the TS
import { SomeEnum } from 'path-to-file'; export class ClassName { readonly SomeEnum = SomeEnum; }
in the HTML use
*ngIf="SomeEnum.someValue === 'abc'"
You'll have to declare it as a property first:
import { Component } from '@angular/core'; import { SomeEnum } from './global'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { name = SomeEnum.someValue; importedSomeEnum = SomeEnum; }
And then use it in the template:
<span *ngIf="name === importedSomeEnum.someValue">This has some value</span>
Here's a Working Demo for your ref.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With