Angular2 - How to use string enums with *ngIf Angular2 - How to use string enums with *ngIf typescript typescript

Angular2 - How to use string enums with *ngIf


As @Buczkowski suggested, you can do it like this:

export enum RoleType {    User = 'User',    Admin = 'Admin'}

component

RoleType = RoleType; // This way you can access its properties from the template.public hasAccess(role: RoleType) {    //check role type and return true or false}

component html

<div id="adminDiv" *ngIf="hasAccess(RoleType.Admin)"></div>

StackBlitz example


Here is a much cleaner way of doing this. Do the following in your component.ts

allRoleTypes = RoleType;

and in your html

*ngIf="role===allRoleTypes.User"

You don't need to write any method.


Get it as a string, then convert it to the RoleType.

public hasAccess(role: string): boolean {const roleAsEnum: RoleType = RoleType[role];return ...}