Last active
November 28, 2017 20:57
-
-
Save sulco/6a7c54d6b7b3e4f6be1ac7dbae579b35 to your computer and use it in GitHub Desktop.
tsIfRole structural directive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from '@angular/core'; | |
import { UserService } from './user.service'; | |
import { UserRole } from '../shared/models/user-role'; | |
@Directive({ | |
selector: '[tsIfRole]' | |
}) | |
export class IfRoleDirective implements OnInit { | |
role: UserRole; | |
constructor(private templateRef: TemplateRef<any>, | |
private userService: UserService, | |
private viewContainer: ViewContainerRef) { | |
} | |
ngOnInit() { | |
this.userService.isAuthenticated.subscribe( | |
(isAuthenticated) => { | |
if (isAuthenticated && this.userService.getCurrentUser().roles.includes(this.role)) { | |
this.viewContainer.createEmbeddedView(this.templateRef); | |
} else { | |
this.viewContainer.clear(); | |
} | |
} | |
); | |
} | |
@Input() set tsIfRole(role: UserRole) { | |
this.role = role; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment