Angular 角度6-自定义指令的多个条件
我制作了一个自定义指令Angular 角度6-自定义指令的多个条件,angular,angular-directive,Angular,Angular Directive,我制作了一个自定义指令[showIfUser],用于根据用户角色显示和隐藏路由。用户有3个角色,分别为“主要”、“替代”和“用户”。一个用户可以有多个角色,并且可以根据其角色查看特定的路由。我的自定义指令仅适用于单个条件,但如何检查指令中的多个条件?例如:这是有效的:,但它不是: custom.directive.ts: @Directive({ selector: '[showIfUser]' }) @AutoUnsubscribe([]) export class ShowIfLogge
[showIfUser]
,用于根据用户角色显示和隐藏路由。用户有3个角色,分别为“主要”、“替代”和“用户”。一个用户可以有多个角色,并且可以根据其角色查看特定的路由。我的自定义指令仅适用于单个条件,但如何检查指令中的多个条件?例如:这是有效的:
,但它不是:
custom.directive.ts:
@Directive({
selector: '[showIfUser]'
})
@AutoUnsubscribe([])
export class ShowIfLoggedInDirective implements OnInit {
@Input() showIfUser;
roleSub = new Subscription();
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private authService: AuthService
) {
}
ngOnInit() {
this.roleSub = this.authService.roles$.subscribe((roles: string[]) => {
this.viewContainer.clear();
if (roles.length && roles.includes(this.showIfUser)) {
if (this.showIfUser) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
} else {
if (!this.showIfUser && !roles.includes('USER') && !roles.includes('PRIMARY') && !roles.includes('SUBSTITUTE')) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
});
}
}
@指令({
选择器:“[showIfUser]”
})
@自动取消订阅([]))
导出类ShowIfLoggeDin指令实现OnInit{
@Input()showIfUser;
roleSub=新订阅();
建造师(
私有templateRef:templateRef,
私有viewContainer:ViewContainerRef,
私有authService:authService
) {
}
恩戈尼尼特(){
this.roleSub=this.authService.roles$.subscribe((角色:string[])=>{
this.viewContainer.clear();
if(roles.length&&roles.includes(this.showIfUser)){
if(this.showIfUser){
this.viewContainer.createEmbeddedView(this.templateRef);
}否则{
this.viewContainer.clear();
}
}否则{
如果(!this.showIfUser&&!roles.includes('USER')&&&!roles.includes('PRIMARY')&&!roles.includes('SUBSTITUTE')){
this.viewContainer.createEmbeddedView(this.templateRef);
}否则{
this.viewContainer.clear();
}
}
});
}
}
该命令不起作用的原因是您在说以下内容时使用了逻辑or运算符
“'PRIMARY'| |'SUBSTITUTE'”
,因此在这种情况下,它将始终返回PRIMARY,因为它是第一个真实值
我建议将指令中的showIfUser变量更改为be和数组类型
@Input() showIfUser:string[];
然后在HTML中
<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>
该函数不起作用的原因是,在表示
“'PRIMARY'| |'SUBSTITUTE'”
,因此在这种情况下,它将始终返回PRIMARY,因为它是第一个真实值
我建议将指令中的showIfUser变量更改为be和数组类型
@Input() showIfUser:string[];
然后在HTML中
<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>