我使用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;
}

我还希望使用*ngIf语句在HTML中使用枚举进行比较:

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

代码编译完成,但浏览器给我一个错误:

无法读取未定义的属性

enter image description here

具有以下html指示错误行:

enter image description here

有人知道为什么不能这样接近enum吗?

推荐答案

模板的范围仅限于组件实例成员. 如果您想引用某项内容,则需要在那里提供

class MyComponent {
  public get connectionResult(): typeof ConnectionResult {
    return ConnectionResult; 
  }
}

在HTML中,您现在可以使用

*ngIf="connectionResult.Success"

另见Angular2 access global variables from HTML template

Html相关问答推荐

CSS自定义特性中的URL是否可以相对于定义的CSS文件?

由于列中的图像,它们不会随FlexBox中的窗口大小进行调整

仅包含名为X的子元素的元素的XPath?

在FlexBox中将div拉伸到父div的完全高度

Bootstrap 5.3.2模式页脚左填充还是左边距?

我正在try 向列表中的图像添加悬停,以放大图像并将div的不透明度设置为1而不是0

我无法动态嵌入Instagram帖子,因为无法分配Instagram固定链接

禁用所有行,但在16角中单击编辑按钮的行除外

SVG的动态CSS

按钮位于主 div 的底部而不是内部 Div

图像如何能达到 HTML 表格的全宽?

水平填充容器内的空间

在React中如何处理HTML本地日期输入?

Sass 混合动画未正确应用

如何并排放置部分?

我如何设置括号的样式,使它们不会挂在旁边的其他字符下面

如何在 svelte 中对静态 html 文件使用href=

如何通过可见文本使用 Selenium 定位元素

发光效果html动画

我如何让这个动画播放,然后停止,然后在设定的时间后再次播放? (CSS)