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
With the following html indication error line:
Does anyone know why the enum cannot be approached like this?
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