Angular 6-自定义指令的多个条件

时间:2018-08-14 12:46:43

标签: angular angular-directive

我创建了一个自定义指令[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();
        }
      }
    });
  }
}

1 个答案:

答案 0 :(得分:1)

无效的原因是您在说逻辑或运算符时 "'PRIMARY' || 'SUBSTITUTE'",因此在这种情况下它将始终返回 primary ,因为它是第一个真实值。

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

@Input() showIfUser:string[];

然后在HTML

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

最后也许可以通过使用

更改您的检查,以查看用户角色是否匹配

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