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