[SOLVED] Use of Enums in Angular 8 HTML template for *ngIf

Issue

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

Solution

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'"

Answered By – Jorge Mussato

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *