Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of Enums in Angular 8 HTML template for *ngIf

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

like image 429
Ling Vu Avatar asked Dec 11 '19 15:12

Ling Vu


People also ask

Can I use enum in template angular?

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.

Can we use enum in HTML angular?

Enums can be used in your Angular templates.

What is the use of ENUM in angular?

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.


2 Answers

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'" 
like image 87
Jorge Mussato Avatar answered Sep 28 '22 09:09

Jorge Mussato


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.

like image 30
SiddAjmera Avatar answered Sep 28 '22 08:09

SiddAjmera