Tom*_*káč 1 angular-directive angular
我想创建自己的身份验证指令,当用户没有所需的角色时隐藏内容。
不幸的是,我得到
Error: Template parse errors:
Can't bind to 'appHasRole' since it isn't a known property of 'div'.
Run Code Online (Sandbox Code Playgroud)
我遵循了每个教程,每个堆栈溢出问题,似乎没有任何帮助。
我创建了指令:
Error: Template parse errors:
Can't bind to 'appHasRole' since it isn't a known property of 'div'.
Run Code Online (Sandbox Code Playgroud)
由于我有多个模块,因此我创建了 SharedModule
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的主页模块中导入该指令(也在app.module中尝试过)
import {NgModule} from '@angular/core';
import {HasRoleDirective} from './directives/has-role.directive';
@NgModule({
declarations: [HasRoleDirective],
exports: [HasRoleDirective]
})
export class SharedModule {
}
Run Code Online (Sandbox Code Playgroud)
最后,使用 home.component.html 中的指令
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 {
}
Run Code Online (Sandbox Code Playgroud)
只需在 中添加 appHasRole 即可@Input,因为它正在寻找hasRole属性。
如果@Input没有参数,Angular 会查找具有 propertyName 的属性。如果将参数传递给@Input,Angular 会查找具有传递的参数值的属性。
@Input('appHasRole')
set hasRole(val) {
this.role = val;
this.updateView();
}
Run Code Online (Sandbox Code Playgroud)