angular - Angular 6 - 自定义指令的多个条件
问题描述
我制作了一个自定义指令[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'"
因此在这种情况下它将始终返回主要值,因为它是第一个真实值。
我建议将指令中的 showIfUser 变量更改为数组类型
@Input() showIfUser:string[];
然后在 HTML
<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>
最后也许更改您的检查以查看用户角色是否匹配使用
if(roles.some(r=> this.showIfUser.includes(r)))
推荐阅读
- sql - 使用 SUBSTRING 和 CHARINDEX 提取部分名称
- powerbi - 在 PowerBI 中将 dBGeography 解析为纬度和经度
- sharepoint - 使用 Graph 对驱动器项目进行多条件查询和过滤
- mips - Verilog。尝试使用 3-AluControl 位扩展数据路径和解码器以进行乘法和 bltz MIPS 指令
- java - 获取 org.apache.hadoop.hive.ql.exec.vector.DecimalColumnVector 无法转换为 org.apache.hadoop.hive.ql.exec.vector.LongColumnVector
- pandas - 有条件地删除重复行 - 啄序
- c# - .Net Core 中 NU1605 警告/错误的可能解决方法
- typescript - 将类导入 Express.js 路由
- docker - Docker:如何取消设置由`docker run -e FOO = bar`命令提供的容器中的环境变量?
- sql - 无法向表中的新列添加值