[英]Angular 6 - multiple conditions for custom directives
我做了一個自定義指令[showIfUser]
,該指令根據用戶的角色顯示和隱藏路由。 用戶有3個角色,分別是'PRIMARY','SUBTITUTE'和'USER'。 用戶可能具有多個角色,並被允許根據其角色查看特定的路由。 我的自定義指令僅適用於單個條件,但是如何檢查指令中的多個條件? 例如: <a href="/" *showIfUser="'PRIMARY'"></a>
: <a href="/" *showIfUser="'PRIMARY'"></a>
,但這<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'"
時使用了邏輯或運算符,因此在這種情況下它將始終返回primary ,因為它是第一個真實值。
我建議將指令中的showIfUser變量更改為和數組類型
@Input() showIfUser:string[];
然后在HTML中
<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>
最后也許通過使用以下命令更改檢查以查看用戶角色是否匹配
if(roles.some(r=> this.showIfUser.includes(r)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.