I've build a 'accessLevel' directive in angular 4 that works like *ngIf but on different levels of permissions.
@Directive({
selector: '[accessLevel]'
})
export class AccessLevelDirective {
private levelToPredicateMapper: {[id: string] : () => Observable<boolean>} = {};
private isAuthorized: boolean;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private readonly credentialsStorage: CredentialsStorageService,
private readonly authentication: AuthenticationService) {
this.createAccessLevelToPredicatesMapper();
}
@Input() set accessLevel(level: string) {
if (level == null) {
return;
}
let hasAccessLevelFunc = this.levelToPredicateMapper[level];
if (hasAccessLevelFunc == null) {
this.viewContainer.clear();
return;
}
hasAccessLevelFunc().subscribe(hasAccessLevel => {
this.buildOrDestroyView(hasAccessLevel);
})
}
@Input() set roles(roles: [string]) {
this.authentication.isAuthenticated()
.subscribe(isAuthenticated => {
let isValidRolesArray = roles != null && Array.isArray(roles) && roles.length > 0;
let isUserHasOneOfTheRoles = isAuthenticated &&
isValidRolesArray &&
this.credentialsStorage.get() &&
some(this.credentialsStorage.get().roles , role => roles.indexOf(role) > -1);
this.buildOrDestroyView(isUserHasOneOfTheRoles);
})
}
private buildOrDestroyView(isAuthorized: boolean) {
let isStateChanged = isAuthorized !== this.isAuthorized;
if (!isStateChanged) return;
this.isAuthorized = isAuthorized;
if (isAuthorized) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
private createAccessLevelToPredicatesMapper() {
this.levelToPredicateMapper['all'] = () => Observable.of(true);
this.levelToPredicateMapper['guest'] = () => this.authentication.isAuthenticated().map(isAuth => !isAuth);
this.levelToPredicateMapper['authenticated'] = () => this.authentication.isAuthenticated()
}
}
My problem is when I use it inside the html . in order to bind to the role property I need to wrap the element with ng-template.
<!--Without [roles]-->
<a class="nav-item nav-link text-uppercase" *accessLevel="'authenticated'">
...
</a>
<!--with [roles]-->
<ng-template accessLevel [roles]="['admin']">
...
</ng-template>
Is there a way I can bind the roles without the need to wrap the element with ng-template?
When the input name is the same as the selector
<input *accessLevel="['admin']" ...
should work
otherwise the input needs to be
@Input() set accessLevelRoles(roles: [string]) {
then
<input *accessLevel="roles:['admin']" ...
should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With