Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 306
Danny Avatar asked Jan 28 '19 11:01

Danny


People also ask

How do I use string enums?

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.

Can enums be strings?

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.

Can I use enum in HTML angular?

Since Angular projects use TypeScript, we can add enums into our project code. to define MyEnum in our component.

Can enums be objects?

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).


2 Answers

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.

like image 134
Dejazmach Avatar answered Sep 29 '22 13:09

Dejazmach


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

like image 28
Silvermind Avatar answered Sep 29 '22 12:09

Silvermind