Cannot approach Typescript enum within HTML

Klyner picture Klyner · May 18, 2017 · Viewed 53.8k times · Source

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?

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · May 18, 2017

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