Issue
How can I use Enums in the Angular 8 template?
component.ts
import { Component } from '@angular/core';
import { SomeEnum } from './global';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = SomeEnum.someValue;
}
component.html
<span *ngIf="name === SomeEnum.someValue">This has some value</value>
This currently doesn't work, since the template has no reference to SomeEnum
. How can I solve it?
ERROR Error: Cannot read property 'someValue' of undefined
Solution
in the TS
import { SomeEnum } from 'path-to-file';
public get SomeEnum() {
return SomeEnum;
}
in the HTML use
*ngIf="SomeEnum.someValue === 'abc'"
EDIT:
Time goes by and we learn more as a developer, the approach I'm using right now doesn't use the get
method.
Both solutions work, just choose the one you like the most.
in the TS
import { SomeEnum } from 'path-to-file';
export class ClassName {
readonly SomeEnum = SomeEnum;
}
in the HTML use
*ngIf="SomeEnum.someValue === 'abc'"
Answered By - Jorge Mussato
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.