Skip to content

Instantly share code, notes, and snippets.

@balvinder294
Created September 7, 2020 07:49
Show Gist options
  • Save balvinder294/8b85cb66e21337ec7aa977f69919b5eb to your computer and use it in GitHub Desktop.
Save balvinder294/8b85cb66e21337ec7aa977f69919b5eb to your computer and use it in GitHub Desktop.
Role based component Display in Angular with directive
import { Component } from '@angular/core';
import { Directive, Input, TemplateRef, ViewContainerRef, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
/**
* @whatItDoes Conditionally includes an HTML element if current user has any
* of the roles passed as the `expression`.
*
* @howToUse
* ```
* <some-element *appHasAnyRole="'ROLE_VALUE'">...</some-element>
*
* <some-element *appHasAnyRole="['ROLE_VALUE_1', 'ROLE_VALUE_2']">...</some-element>
* ```
*/
@Directive({
selector: '[appHasAnyRole]'
})
export class HasAnyAppRoleComponentDirective {
private roles: string[] = [];
constructor(private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) {}
@Input()
set appHasAnyRole(value: string | string[]) {
// check if single role supplied or multiple roles and assign to variable
this.roles = typeof value === 'string' ? [value] : value;
// before showing again call to prevent duplicates
this.updateView();
// Get notified each time authentication state changes
// replace api with your authentication check
yourAuthentication
.subscribe(() => {this.updateView()})
}
private updateView(): void {
const hasAnyRole = this.checkRole(this.roles);
// clear any old reference to prevnt duplication
this.viewContainerRef.clear();
// show content if role true, else dont. this is the main logic
if (hasAnyRole) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
}
}
checkRole(roles: string[] | string): boolean {
// call your api to get user/account DTo for your current logged in user
// change yourAccount with your variable
// role/roles with your property having the role value
// if you have single role check, convert it to array
if (!Array.isArray(roles)) {
roles = [roles];
}
// let say you have user.roles as Array strings in your table, then do
return yourAccount.roles.some((role: string) => roles.includes(role));
// let say you have single role in your Db
return roles.include(yourAccount.role);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment