无法在HTML中使用Typescript枚举

前端之家收集整理的这篇文章主要介绍了无法在HTML中使用Typescript枚举前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Typescript创建了一个枚举,用于MyService.service.ts MyComponent.component.ts和MyComponent.component.html. @H_502_2@export enum ConnectionResult { Success,Failed }

我可以轻松地从MyService.service.ts获取并比较定义的枚举变量:

@H_502_2@this.result = this.myService.getConnectionResult(); switch(this.result) { case ConnectionResult.Failed: doSomething(); break; case ConnectionResult.Success: doSomething(); break; }

我还想使用enum在我的HTML中使用* ngIf语句进行比较:

@H_502_2@<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>

代码编译但浏览器给我一个错误

Cannot read property of undefined

使用以下html指示错误行:

有谁知道为什么不能像这样接近枚举?

解决方法

模板的范围仅限于组件实例成员.
如果你想参考那里需要的东西 @H_502_2@class MyComponent { connectionResult = ConnectionResult; }

那你可以用

@H_502_2@*ngIf="connectionResult.Success"

另见Angular2 access global variables from HTML template

猜你在找的TypeScript相关文章