无法在 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;
}

我还想使用枚举在我的 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>

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

无法读取未定义的属性

在此处输入图像描述

带有以下 html 指示错误行:

在此处输入图像描述

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

原文由 Klyner 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

模板的范围仅限于组件实例成员。如果你想引用它需要在那里可用的东西

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

在 HTML 中,您现在可以使用

*ngIf="connectionResult.Success"

另请参阅 Angular2 从 HTML 模板访问全局变量

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 4.0 许可协议

模板的范围仅限于组件实例成员。如果你想参考它需要在那里可用的东西

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

在 HTML 中,您现在可以使用

*ngIf="connectionResult.Success"

另见 Angular2 从 HTML 模板访问全局变量

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题