微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在HTML中使用Typescript枚举

我使用Typescript创建了一个枚举,用于MyService.service.ts MyComponent.component.ts和MyComponent.component.html.
export enum ConnectionResult {
    Success,Failed     
}

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

this.result = this.myService.getConnectionResult();

switch(this.result)  
{
    case ConnectionResult.Failed:
         doSomething();
         break;
    case ConnectionResult.Success:
         doSomething();
         break;
}

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

<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指示错误行

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

解决方法

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

那你可以用

*ngIf="connectionResult.Success"

另见Angular2 access global variables from HTML template

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐