我创建此指令是为了验证用户显示菜单项或隐藏菜单的权限
这是我的代码:
@Directive({
selector: '[Permission]'
})
export class Pemsittiondirective {
@Input() AccessName: string;
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef,
private permission: PermissionValidate
) {
console.log(this.AccessName)
this.show();
}
show(): void {
console.log('in d')
if (this.permission.validateAccessLevel(this.AccessName)) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
}
}
}
我在 HTML 中使用这个指令:
<li [Permission]='User:Main' class="side-menu-items-item">
<div class="item-icon">
<i nz-icon nzType="team" nzTheme="outline"></i>
</div>
<div class="item-label">
<label>{{'DASHBOARD.MENU_ITEM.USER_MANAGER' | translate}}</label>
</div>
</li>
[权限]='用户:主'
shared.module 中的 i 声明:
declarations: [ShowErrorComponent,Pemsittiondirective],
imports: [
CommonModule,
MaterialModule,
ZorroModule,
],
exports: [MaterialModule,Pemsittiondirective]
})
但是它不起作用,并且没有进入指令
有什么问题吗?我该如何解决它??? 更新问题:
这是我的shared.module
@NgModule({
declarations: [ShowErrorComponent,Pemsittiondirective,EmailExistValidationDirective,UsernameValidationDirective],
imports: [
CommonModule,
MaterialModule,
ZorroModule,
],
exports: [MaterialModule,Pemsittiondirective,ZorroModule ,ShowErrorComponent,EmailExistValidationDirective,UsernameValidationDirective]
})
export class SharedModule {
static forRoot(): ModuleWithProviders {
// Forcing the whole app to use the returned providers from the AppModule only.
return {
ngModule: SharedModule,
providers: [ShowErrorComponent ,Pemsittiondirective , EmailExistValidationDirective ,UsernameValidationDirective/* All of your services here. It will hold the services needed by `itself`. */]
};
}
}
最佳答案
我认为问题在于将值传递给指令属性Directive="User:Main"
。
在 guide通过 Angular,他们这样做:
@Directive({
selector: '[appPermission]'
})
export class Pemsittiondirective {
constructor(
private templateRef: TemplateRef<any>,
private viewContainerRef: ViewContainerRef,
private permission: PermissionValidate
) {
}
@Input() set appPermission(accessName: string) {
if (this.permission.validateAccessLevel(accessName)) {
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.viewContainerRef.clear();
}
}
}
The directive consumer expects to bind a true/false condition to [appUnless]. That means the directive needs an appUnless property, decorated with @Input
Angular Says in the Guide
正如 @Stavm 已经提到的 - 这是一个结构指令。因此您需要使用*
。
然后你就可以使用它了:
<li *appPermission='"User:Main"' class="side-menu-items-item"></li>
这是我制作的一个示例:https://stackblitz.com/edit/angular-gjewlg
这个例子正在运行。
关于javascript - 不输入指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59423145/