在 Angular html 模板中访问常量枚举

ren*_*thy 6 html enums templates typescript angular

假设我有一个 const 枚举:

export const enum MyConstEnum{
    Value1 = 'Value1',
    Value2 = 'Value2',
    Value3 = 'Value3'
}
Run Code Online (Sandbox Code Playgroud)

现在我想在我的 Angular 模板中使用它:

<span *ngIf="name === MyConstEnum.Value1">This has some value</value>
Run Code Online (Sandbox Code Playgroud)

但是,这是不可能的,因为MyConstEnum模板看不到。所以问题是如何const enum在Angular html模板中访问?

如果枚举不会像这样 const

export enum MyEnum{
    Value1 = 'Value1',
    Value2 = 'Value2',
    Value3 = 'Value3'
}
Run Code Online (Sandbox Code Playgroud)

有一个在模板组件中创建属性的解决方案

  public get MyEnumInComponent() {
    return MyEnum;
  }
Run Code Online (Sandbox Code Playgroud)

并且MyEnumInComponent可以在 HTML 中访问。但是,我有const enum.

为此,我无法像上面那样定义属性。解决方案是什么(除了更改const enumenum)?

Apu*_*hak 1

我可以在此链接https://github.com/angular/angular/issues/25963上看到 它是已知问题,并且专门针对 const 枚举。

在此输入图像描述

There is also a work arround suggested in the discussion on the url:
templateImports: [someConstant, UserStatus, isDevMode]
This would not work, but the below could:

templateImports: {someConstant, UserStatus, isDevMode}
Run Code Online (Sandbox Code Playgroud)

  • 你自己尝试过吗?这只是建议,并没有实施 (3认同)