Angular 2 Directive – Show Content Based on the User Role


Show Content Based on the User Role —

Imagine that you need to show/hide content based on the user role. Let’s say you have a user stream that will give you the current user and you want to determine if he has permission to see the content based on his role.

“`

@Directive({selector: ‘[ifRole]’})
export class IfRoleDirective {
user$ : Subscription;
@Input(“ifRole”) roleName : string;

constructor( private templateRef : TemplateRef<any>,
private viewContainer : ViewContainerRef,
private authService : AuthService ) {
}

ngOnInit() {
this.user$ = this.authService.user
.do(() => this.viewContainer.clear())
.filter(user => user.role === this.roleName).subscribe(() => {
this.viewContainer.createEmbeddedView(this.templateRef);
});
}

ngOnDestroy() {
this.user$.unsubscribe();
}
}
“`

NoteauthService.user returns an observable.

The usage —

“`

Only for Admin
Only for Client
Only for Editor

“`

 

Very cool 😎 !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s