我使用的是最新版本的Angular
,并尝试访问HTML中的const枚举,我不知道该怎么做。这是枚举
export const enum InputTypes {
DragDrop = "dragDrop",
Text = "text",
Search = "search"
}
由于枚举导出问题,我需要在enum
前面声明const
。我尝试过的
*ngIf="inputTypes.Search"
第一种方法
export class ChipsComponent implements OnInit {
constructor() { }
ngOnInit(): void {}
public get inputTypes(): typeof InputTypes {
return InputTypes;
}
}
第二种方法
export class ChipsComponent implements OnInit {
constructor() { }
ngOnInit(): void {}
inputTypes = InputTypes;
}
错误
'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query
tsconfig.json
"compilerOptions": {
"preserveConstEnums": true
}
如果我没有将枚举声明为const,那么上面的方法会起作用,但不确定const值
有一个悬而未决的问题https://github.com/angular/angular/issues/25963一种解决方案是
templateImports: [someConstant, UserStatus, isDevMode]
这是行不通的,但以下可以:
templateImports: {someConstant, UserStatus, isDevMode}
即使这个也不起作用,在templateImports
上出现错误
TypeScript支持Literal Types,这是一种常量字符串,将该功能与Unions结合在一起,您的结构与枚举非常相似,但问题要小得多。
示例:
type InputTypes = 'dragDrop' | 'text' | 'search';
export class ChipsComponent {
@Input() appType: AppType;
}
<div *ngIf="appType === 'text'">
...
</div>
Literal Types只是预先定义的字符串,所以在Angular Templates上使用它没有问题,它甚至可以在您想要的编辑器/IDE上完成代码。有趣的是,TypeScript编译器会阻止任何使用与您定义的字符串值不同的字符串值的编译。