Cannot approach Typescript enum within HTML

97,723

Solution 1

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

Solution 2

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. :)

Solution 3

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

Solution 4

import MyEnum from enums;  

.... Declarate var ....

public myEnum = MyEnum;

and in html use:

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

Solution 5

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

Share:
97,723
Klyner
Author by

Klyner

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”

Updated on May 06, 2022

Comments

  • Klyner
    Klyner about 2 years

    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?

  • Nasrul Bharathi
    Nasrul Bharathi almost 6 years
    Since I am strictly following the coding standards, what data type , I have to give for the connectionResult
  • Günter Zöchbauer
    Günter Zöchbauer almost 6 years
    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?
  • Nasrul Bharathi
    Nasrul Bharathi almost 6 years
    Thanks, let me start a new conversation in stack overflow
  • Kon
    Kon about 5 years
    Yes, just a plain property member didn't work for me, but setting it as a getter worked.
  • Jacques
    Jacques over 4 years
    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
  • LosManos
    LosManos about 4 years
    Not as in other answer that you can keep the name. (might create other problems though, ones I have not discovered yet)
  • LosManos
    LosManos about 4 years
    If you want to output the name of the enum, like in a div or mat-icon you have to reference the enum, and not the item directly. Easier to show than explain: <mat-icon svgIcon="{{Quarters[Quarters.Q1]}}"></mat-icon>
  • Nikhil Gupta
    Nikhil Gupta almost 4 years
    @NasrulBharathi The return type will be typeof ConnectionResult.
  • d3vtoolsmith
    d3vtoolsmith almost 4 years
    this is definitely the cleanest way
  • super IT guy
    super IT guy over 3 years
    I believe all enums come with numbers automatically
  • Pawel Cioch
    Pawel Cioch over 3 years
    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
    Pawel Cioch over 3 years
  • smartmouse
    smartmouse almost 3 years
    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.
  • harishr
    harishr over 2 years
    This option is way better than others...
  • Aaron Ullal
    Aaron Ullal about 2 years
    Why do I get: This condition will always return 'false' since the types <enum values> have no overlap.?
  • Mark
    Mark about 2 years
    Simple easy solution. This should be the accepted answer.