I wanted to create my own authentication directive, that hides content when user doesn't have the desired role.
Unfortunatelly, I get
Error: Template parse errors:
Can't bind to 'appHasRole' since it isn't a known property of 'div'.
I followed every tutorial, every stack overflow question, nothing seem to help.
I have created the directive:
import {Directive, ElementRef, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {AuthService} from '../../../security/auth.service';
@Directive({
selector: '[appHasRole]'
})
export class HasRoleDirective {
role: string;
constructor(private element: ElementRef,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private authService: AuthService) { }
private updateView() {
if (this.checkPermission()) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
private checkPermission() {
// logic for determining role
}
@Input()
set hasRole(val) {
this.role = val;
this.updateView();
}
}
Since I have multiple modules, I created SharedModule
import {NgModule} from '@angular/core';
import {HasRoleDirective} from './directives/has-role.directive';
@NgModule({
declarations: [HasRoleDirective],
exports: [HasRoleDirective]
})
export class SharedModule {
}
Then importing the directive in my home page module (also tried it in the app.module)
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {HomeComponent} from './home/home.component';
import {SharedModule} from '../shared/shared.module';
@NgModule({
declarations: [HomeComponent],
imports: [
CommonModule,
...
SharedModule
]
})
export class HomeModule {
}
And finally, using the directive in home.component.html
<div class="button-group" *appHasRole="['admin']">
...
Just add appHasRole in @Input
, because it was looking for hasRole
attribute.
If @Input
doesn't have parameter Angular looks for an attribute with propertyName. If you pass parameter to the @Input
, Angular looks for an attribute with the value of parameter passed.
@Input('appHasRole')
set hasRole(val) {
this.role = val;
this.updateView();
}