Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
960 views
in Technique[技术] by (71.8m points)

angular - Cannot approach Typescript enum within HTML

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...