Angular2 - How to use string enums with *ngIf
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>
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>
Comments
-
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 over 5 yearsThanks for the solution. But doesn't this just makes the enum redundant then??
-
Hypenate over 5 yearsI suppose it would :) I would lean more to the idea of R. Richards.
-
aBnormaLz over 5 yearsYou added an answer similar to @veben's answer
-
Ganz over 5 yearsyes i guess we where all. rigth, i didn't see is answer before
-
MDMoore313 about 3 yearsMuch cleaner indeed.