Skip to content

Instantly share code, notes, and snippets.

@sulco
Last active November 28, 2017 20:57
Show Gist options
  • Save sulco/6a7c54d6b7b3e4f6be1ac7dbae579b35 to your computer and use it in GitHub Desktop.
Save sulco/6a7c54d6b7b3e4f6be1ac7dbae579b35 to your computer and use it in GitHub Desktop.
tsIfRole structural directive
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