Danny
Danny

Reputation: 9634

Angular2 - How to use string enums with *ngIf

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?

Upvotes: 21

Views: 27061

Answers (6)

Dejazmach
Dejazmach

Reputation: 800

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.

Upvotes: 33

Ganz
Ganz

Reputation: 76

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>

Upvotes: 2

veben
veben

Reputation: 22302

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>

Upvotes: 2

Silvermind
Silvermind

Reputation: 5944

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

Upvotes: 25

Shadab Faiz
Shadab Faiz

Reputation: 2508

The Error appears because you are passing String when an enum is expected. As others have suggested, there are multiple ways to handle it and one of them is:

  private hasRole(role: string) {
    console.log(role == RoleType.admin);
    console.log(role == RoleType.user);
  }

Upvotes: 0

Hypenate
Hypenate

Reputation: 2064

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

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

return ...
}

Upvotes: 3

Related Questions