首页 > 解决方案 > 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();
        }
      }
    });
  }
}

标签: angularangular-directive

解决方案


不起作用的原因是您在说时使用了逻辑或运算符, "'PRIMARY' || 'SUBSTITUTE'"因此在这种情况下它将始终返回主要值,因为它是第一个真实值。

我建议将指令中的 showIfUser 变量更改为数组类型

@Input() showIfUser:string[];

然后在 HTML

<a href="/link" *showIfUser="['PRIMARY','SUBSTITUTE']"></a>

最后也许更改您的检查以查看用户角色是否匹配使用

if(roles.some(r=> this.showIfUser.includes(r)))

推荐阅读