如何匹配ts中的变量和html中的Directive值?

时间:2017-06-17 11:41:22

标签: angular typescript

有一个指令,其中以下代码匹配结果,如果并将内容隐藏给具有其他角色的用户

import {
  Directive,
  Input,
  OnInit,
  TemplateRef,
  ViewContainerRef
} from '@angular/core';

import { ActivatedRoute } from '@angular/router';
import { User, UserService, Profile, ProfilesService } from '../shared';

@Directive({ selector: '[userRoles]' })
export class UserRolesDirective implements OnInit {
  constructor(
    private templateRef: TemplateRef<any>,
    private userService: UserService,
    private viewContainer: ViewContainerRef,
    private route: ActivatedRoute,
    private profilesService: ProfilesService
  ) {}

  profile: Profile;
  roles: string;
  currentUser: User;


  ngOnInit() {
            this.route.data.subscribe(
              (data: {profile: Profile}) => {
                this.profile = data.profile;
                this.userService.currentUser.subscribe(
                  (userData: User) => {
                    this.currentUser = userData;
                    console.log(this.currentUser.roles);
                    if (this.currentUser.roles == ) {
                        this.viewContainer.createEmbeddedView(this.templateRef);
                    } else {
                        this.viewContainer.clear();
                  }
                  }
                );
              }
            );
  }

  @Input() set userRoles(roles: string) {
    this.roles = roles;
  }

}

有html代码,我输出此指令的值

<div class="col-sm-12" *userRoles="['Admin']">
        <div class="feed-toggle mt-3">
          <ul class="nav nav-pills outline-active">
            <li class="nav-item">
              <a class="nav-link"
                 [ngClass]="{'active': listConfig.type === 'feed'}"
                 (click)="setListTo('feed')">

大家帮忙,我如何匹配this.currentUser.roles和userRoles结果 索引不工作,或者我做错了。

!this.userRoles || this.userRoles.indexOf(this.currentUser.roles) != -1

PS:如果我在页面上有多个指令,系统会工作吗?

1 个答案:

答案 0 :(得分:0)

this.currentUser.roles == this.role[0]