Angular2 - How to use string enums with *ngIf

14,773

Solution 1

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

Solution 2

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.

Solution 3

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

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

return ...
}

Solution 4

You should not use function with parameter in the template, but do something like that:

Declare a var isAdmin in your .ts file, and initialize it at the creation of the component, checking if the user is admin:

isAdmin = false;
ngOnInit() {
    this.isAdmin = this.checkIfUserAdmin(...)
}

Use it in the *ngIf:

<div id="adminDiv" *ngIf="isAdmin">
</div>

Solution 5

you can use another var, something like AdminTest in your .ts file, and set a value to it at the ngOnInit hook.

you should have something like :

.ts:

AdminTest = false;

ngOnInit() {
    this.AdminTest = this.checkRole()
}

checkRole() {
    // ...
}

.html:

<div id="adminDiv" *ngIf="AdminTest"></div>
Share:
14,773
Danny
Author by

Danny

A student learning about game programming and development

Updated on June 07, 2022

Comments

  • Danny
    Danny almost 2 years

    How do I pass enum to a function when I use *ngIf in Angular?

    I have the follow code:

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

    component function

    public hasAccess(role: RoleType) {
       //check role type and return true or false
    }
    

    component html

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

    When I build this, it keeps complaining. It cannot convert the string to the enum, is there a way around this?

  • Danny
    Danny over 5 years
    Thanks for the solution. But doesn't this just makes the enum redundant then??
  • Hypenate
    Hypenate over 5 years
    I suppose it would :) I would lean more to the idea of R. Richards.
  • aBnormaLz
    aBnormaLz over 5 years
    You added an answer similar to @veben's answer
  • Ganz
    Ganz over 5 years
    yes i guess we where all. rigth, i didn't see is answer before
  • MDMoore313
    MDMoore313 about 3 years
    Much cleaner indeed.