Reputation: 5355
Assume I have a const enum:
export const enum MyConstEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
Now I want to use it in my Angular template:
<span *ngIf="name === MyConstEnum.Value1">This has some value</value>
However, this is not possible, because MyConstEnum
is not seen by template.
So the question is how to access const enum
in Angular html template?
If enum won't be const like this
export enum MyEnum{
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
there is a solution to create property in templates' component
public get MyEnumInComponent() {
return MyEnum;
}
and MyEnumInComponent
will be accessible in HTML.
However, I have const enum
.
For this I cannot defined property like above. What is the solution (except changing const enum
to enum
)?
Upvotes: 14
Views: 6664
Reputation: 7
You can create a property of the same name as the enum inside your component and you'd be able to access the enum just as you would within your ts file. You can do this by either importing it or declaring it within the ts file if preferred:
import { MyConstEnum } from './enum'
OR
enum MyConstEnum {
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
@Component({
selector: 'app-my-component',
templateUrl: './my-component.page.html',
styleUrls: ['./my-component.page.scss'],
})
export class MyComponent {
MyConstEnum = MyConstEnum;
...
}
And within the html template:
<span *ngIf="name === MyConstEnum.Value1">{{ MyConstEnum.Value1 }}</value>
Upvotes: -1
Reputation: 1410
I bypassed this issue by replacing my const enum types to static properties inside classes like this:
export class MyEnum{
static Value1 = 'Value1',
static Value2 = 'Value2',
static Value3 = 'Value3'
}
Upvotes: -2
Reputation: 766
I can see on this link https://github.com/angular/angular/issues/25963 that it is known issue and it is specifically with const enum.
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}
Upvotes: 1
Reputation: 214095
It will be possible if TypeScript won't erase const enum declaration in the emitted JavaScript code.
There is dedicated compiler options preserveConstEnums
for that:
tsconfig.json
{
"compilerOptions": {
...
"preserveConstEnums": true,
...
},
...
}
Now, let's say you have
const-enum.ts
export const enum MyConstEnum {
Value1 = 'Value1',
Value2 = 'Value2',
Value3 = 'Value3'
}
You can import it in component like:
import * as constEnumModule from './const-enum';
class SomeComponent {
MyConstEnum = (constEnumModule as any).MyConstEnum;
}
It finally it should be available in your template for this component:
<span *ngIf="name === MyConstEnum.Value1">This has some value</value>
Upvotes: 3