Angular 6 - 自定义指令的多个条件
Angular 6 - multiple conditions for custom directives
我创建了一个自定义指令 [showIfUser]
来根据用户的角色显示和隐藏路由。用户有 3 个角色 'PRIMARY'、'SUBTITUTE' 和 'USER'。一个用户可能有多个角色,并允许根据他们的角色查看特定的路线。我的自定义指令仅适用于单个条件,但如何检查指令中的多个条件?例如:这行得通:<a href="/" *showIfUser="'PRIMARY'"></a>
,但行不通:<a href="/link" *showIfUser="'PRIMARY' || 'SUBSTITUTE'"></a>
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();
}
}
});
}
}
不起作用的原因是您在说时使用了逻辑或运算符
"'PRIMARY' || 'SUBSTITUTE'"
因此在这种情况下它将始终 return 主要 因为它是第一个真实值。
我建议将指令中的 showIfUser 变量更改为数组类型
@Input() showIfUser:string[];
然后在 HTML
<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>
最后也许可以更改您的检查以查看用户角色是否匹配,方法是使用
if(roles.some(r=> this.showIfUser.includes(r)))
我创建了一个自定义指令 [showIfUser]
来根据用户的角色显示和隐藏路由。用户有 3 个角色 'PRIMARY'、'SUBTITUTE' 和 'USER'。一个用户可能有多个角色,并允许根据他们的角色查看特定的路线。我的自定义指令仅适用于单个条件,但如何检查指令中的多个条件?例如:这行得通:<a href="/" *showIfUser="'PRIMARY'"></a>
,但行不通:<a href="/link" *showIfUser="'PRIMARY' || 'SUBSTITUTE'"></a>
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();
}
}
});
}
}
不起作用的原因是您在说时使用了逻辑或运算符
"'PRIMARY' || 'SUBSTITUTE'"
因此在这种情况下它将始终 return 主要 因为它是第一个真实值。
我建议将指令中的 showIfUser 变量更改为数组类型
@Input() showIfUser:string[];
然后在 HTML
<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>
最后也许可以更改您的检查以查看用户角色是否匹配,方法是使用
if(roles.some(r=> this.showIfUser.includes(r)))