无法在 HTML 中处理 Typescript 枚举 [英] Cannot approach Typescript enum within HTML

查看:28
本文介绍了无法在 HTML 中处理 Typescript 枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Typescript 做了一个枚举,用于 MyService.service.ts MyComponent.component.ts 和 MyComponent.component.html.

export enum ConnectionResult {成功,失败的}

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

this.result = this.myService.getConnectionResult();开关(this.result){案例 ConnectionResult.Failed:做一点事();休息;案例 ConnectionResult.Success:做一点事();休息;}

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

<img src="../../assets/connection-success.png" height="300px" class="image-sign-style"/>

<ng-template #failed><img src="../../assets/connection-failed.png" height="300px" class="image-sign-style"/></ng-模板>

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

<块引用>

无法读取未定义的属性

带有以下html指示错误行:

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

解决方案

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

class MyComponent {public get connectionResult(): typeof ConnectionResult {返回连接结果;}}

您现在可以在 HTML 中使用

*ngIf=connectionResult.Success"

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

I made an enum with Typescript to use in MyService.service.ts MyComponent.component.ts and MyComponent.component.html.

export enum ConnectionResult {
    Success,
    Failed     
}

I can easily get and compare a defined enum variable from MyService.service.ts:

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

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

I also wanted to use the enum for a comparison within my HTML using the *ngIf statement:

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

The code compiles but the browser gives me an error:

Cannot read property of undefined

With the following html indication error line:

Does anyone know why the enum cannot be approached like this?

解决方案

The scope of the template is limited to the component instance members. If you want to refer to something it needs to be available there

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

In the HTML you can now use

*ngIf="connectionResult.Success"

See also Angular2 access global variables from HTML template

这篇关于无法在 HTML 中处理 Typescript 枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆