Use of Enums in Angular 8 HTML template for *ngIf

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.


You can declare a field equal to the SomeEnum enum (it may be imported from another file) as a public class field in the component file. Then it will be accessible in the template.

// component 
export class AppComponent  {
  name = SomeEnum.someValue;
  enum = SomeEnum;
}

// template
<span *ngIf="name === enum.someValue">This has some value</value>

Yes, the template cannot refer to the enum directly. There are few ways to do this. 1. Add Enum reference to the component ts file like below

someEnum = SomeEnum;

then you will be able to use the reference in your template like this

<span *ngIf="name === someEnum.someValue">This has some value</value>
  1. The second way is to call a function from your template with name as parameter and compare it in the typescript file

<span *ngIf="checkCondition(name)">This has some value</value>