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?
In summary, to make use of string-based enum types, we can reference them by using the name of the enum and their corresponding value, just as you would access the properties of an object. At runtime, string-based enums behave just like objects and can easily be passed to functions like regular objects.
In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member. While string enums don't have auto-incrementing behavior, string enums have the benefit that they “serialize” well.
Since Angular projects use TypeScript, we can add enums into our project code. to define MyEnum in our component.
An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
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.
As @Buczkowski suggested, you can do it like this:
export enum RoleType {
User = 'User',
Admin = 'Admin'
}
RoleType = RoleType; // This way you can access its properties from the template.
public hasAccess(role: RoleType) {
//check role type and return true or false
}
<div id="adminDiv" *ngIf="hasAccess(RoleType.Admin)">
</div>
StackBlitz example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With