[英]Accessing const enums in Angular html template
假設我有一個 const 枚舉:
export const enum MyConstEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
現在我想在我的 Angular 模板中使用它:
<span *ngIf="name === MyConstEnum.Value1">This has some value</value>
但是,這是不可能的,因為模板看不到MyConstEnum
。 所以問題是如何訪問 Angular html 模板中的const enum
?
如果枚舉不是這樣的 const
export enum MyEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
有一個在模板組件中創建屬性的解決方案
public get MyEnumInComponent() {
return MyEnum;
}
和MyEnumInComponent
將在 HTML 中訪問。但是,我有const enum
。
為此,我無法像上面那樣定義屬性。 解決方案是什么(除了將const enum
更改為enum
)?
我可以在這個鏈接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}
如果 TypeScript 不會刪除發出的 JavaScript 代碼中的常量枚舉聲明,則有可能。
為此有專門的編譯器選項preserveConstEnums
:
tsconfig.json
{
"compilerOptions": {
...
"preserveConstEnums": true,
...
},
...
}
現在,假設你有
const-enum.ts
export const enum MyConstEnum {
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
您可以將其導入組件中,例如:
import * as constEnumModule from './const-enum';
class SomeComponent {
MyConstEnum = (constEnumModule as any).MyConstEnum;
}
它最終應該在您的模板中用於此組件:
<span *ngIf="name === MyConstEnum.Value1">This has some value</value>
假設我有一個常量枚舉:
export const enum MyConstEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
現在我想在我的 Angular 模板中使用它:
<span *ngIf="name === MyConstEnum.Value1">This has some value</value>
但是,這是不可能的,因為模板看不到MyConstEnum
。 所以問題是如何訪問 Angular html 模板中的const enum
?
如果枚舉不是這樣的 const
export enum MyEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
有一種在模板組件中創建屬性的解決方案
public get MyEnumInComponent() {
return MyEnum;
}
和MyEnumInComponent
可以在 HTML 中訪問。 但是,我有const enum
。
為此,我無法像上面那樣定義屬性。 解決方案是什么(除了將const enum
更改為enum
)?
我通過將我的常量枚舉類型替換為類中的 static 屬性來繞過這個問題,如下所示:
export class MyEnum{
static Value1 = 'Value1',
static Value2 = 'Value2',
static Value3 = 'Value3'
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.