171

I made an enum with Typescript to use in MyService.service.ts MyComponent.component.ts and MyComponent.component.html.

export enum ConnectionResult {
    Success,
    Failed     
}

I can easily get and compare a defined enum variable from MyService.service.ts:

this.result = this.myService.getConnectionResult();

switch(this.result)  
{
    case ConnectionResult.Failed:
         doSomething();
         break;
    case ConnectionResult.Success:
         doSomething();
         break;
}

I also wanted to use the enum for a comparison within my HTML using the *ngIf statement:

<div *ngIf="result == ConnectionResult.Success; else failed">
            <img src="../../assets/connection-success.png" height="300px" class="image-sign-style" />
</div>
<ng-template #failed>
       <img src="../../assets/connection-failed.png" height="300px" class="image-sign-style" />
</ng-template>

The code compiles but the browser gives me an error:

Cannot read property of undefined

enter image description here

With the following html indication error line:

enter image description here

Does anyone know why the enum cannot be approached like this?

Klyner
  • 3,983
  • 4
  • 26
  • 50

9 Answers9

293

The scope of the template is limited to the component instance members. If you want to refer to something it needs to be available there

class MyComponent {
  public get connectionResult(): typeof ConnectionResult {
    return ConnectionResult; 
  }
}

In the HTML you can now use

*ngIf="connectionResult.Success"

See also Angular2 access global variables from HTML template

Hypenate
  • 1,907
  • 3
  • 22
  • 38
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Since I am strictly following the coding standards, what data type , I have to give for the connectionResult – Nasrul Bharathi Jun 28 '18 at 10:59
  • I don't know. I only used TypeScript in Plunker and there were no type checks. I'd expect the error message tells you the expected type when you use an incompatible one, doesn't it? – Günter Zöchbauer Jun 28 '18 at 11:08
  • Thanks, let me start a new conversation in stack overflow – Nasrul Bharathi Jun 28 '18 at 11:10
  • 1
    Yes, just a plain property member didn't work for me, but setting it as a getter worked. – Kon Feb 11 '19 at 19:08
  • 2
    Not as in [other answer](https://stackoverflow.com/a/56182063/521554) that you can keep the name. (might create other problems though, ones I have not discovered yet) – LosManos Mar 12 '20 at 07:32
  • @NasrulBharathi The return type will be `typeof ConnectionResult`. – Nikhil Gupta Jul 05 '20 at 17:06
  • 5
    None here with this error? `error TS2475: 'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query.` – smartmouse Jul 07 '21 at 10:54
92

You will have to write it in the following way in .ts file.

enum Tenure { day, week, all }

export class AppComponent {
    tenure = Tenure.day
    TenureType = Tenure
}

And now in html you can use this like

*ngIf = "tenure == TenureType.day ? selectedStyle : unSelectedStyle"

I hope it is more clear now. :)

Nikhil Manapure
  • 3,748
  • 2
  • 30
  • 55
  • 8
    Don't forget to use '=' and not ':', between TenureType and Tenure, i.e. assign the type don't define it. I just made that mistake overlooking what @Nikhil had written. +1 – Jacques Nov 25 '19 at 13:04
  • 1
    Simple easy solution. This should be the accepted answer. – Mark Mar 30 '22 at 13:31
59

You can just add the enum to your component as property and use the same name of the enum (Quarters) in your templates:

enum Quarters{ Q1, Q2, Q3, Q4}

export class AppComponent {
   quarter = Quarters.Q1
   Quarters = Quarters //here you are creating a variable/alias to the enum
}

In your template

<div *ngIf="quarter == Quarters.Q1">I=am only visible for Q1</div> 

The reason why this works is that the new porperty is basically of this type:

TileType: typeof TileType
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
Ondrej Peterka
  • 3,349
  • 4
  • 35
  • 49
21
import MyEnum from enums;  

.... Declarate var ....

public myEnum = MyEnum;

and in html use:

<div *ngIf="xxx === myEnum.DATA"> ... </div>
5

In your Service

export enum ConnectionResult {
    Success,
    Failed     
}

Assign the enum to a varaible in TypeScript File

ConnectionResult = ConnectionResult; 

Then read your Enum from HTML as bellow

*ngIf="result == ConnectionResult.Success"
Dimuth
  • 713
  • 2
  • 11
  • 34
2

You can bind as text if enum defined as below (those values won't enforce a json string value coming from API)

  export enum SomeEnum {
      Failure = "Failure",
      Success = "Success",
  }

In .ts file

public status: SomeEnum;

In .html

<div *ngIf="status == 'Success'">

Another way, tested in Angular 8+ is to have enums with numbers

  export enum SomeEnum {
      Failure = 0,
      Success = 1,
  }

In .ts file

public status: SomeEnum;

In .html

<div *ngIf="status == 1">

Jöcker
  • 5,281
  • 2
  • 38
  • 44
Pawel Cioch
  • 2,895
  • 1
  • 30
  • 29
  • 1
    I believe all enums come with numbers automatically – super IT guy Nov 13 '20 at 15:08
  • 1
    You can believe what you want but I tested it and thus provided 2 approaches. So no, if you don't specify a number it does not come with a number like in C#. This could behavior may be subject to TypeScript version (+ maybe Angular frx version) – Pawel Cioch Nov 16 '20 at 21:58
  • https://www.tutorialsteacher.com/typescript/typescript-enum – Pawel Cioch Dec 18 '20 at 17:53
1

Most common mistake coders do while using enum if they want to use it in html files they declare like below which is often overlooked.

  myEnum : MyEnum

Please notice that its not colon(:), instead an assignment operator has to be used like below:

myEnum = MyEnum

Just now sat with my colleague to solve this issue , and it took half an hour to debug this because of just one char (using : instead of =).

Sarwan
  • 595
  • 3
  • 8
  • 21
0

in component:

 export class LevelsFieldsComponent implements OnInit {
  grades: GradeDto[]; // add enumn in class of Component
  constructor() { }
 }

in html:

*ngIf="gradeId == gradeEnum.Cool"
M Komaei
  • 7,006
  • 2
  • 28
  • 34
0

Another option is to declare a type that holds the type of the enum. example:

export enum Icons {
 Icon1 = 'Icon1',
 Icon2 = 'Icon2'
}
export type IconsType = typeof Icons;

Then in the component:

class MyComponent {
  icons: IconsType = Icons;
}

Or Shalmayev
  • 295
  • 1
  • 12