在ng6中,我的指令不会刷新我的组件

时间:2018-10-16 07:16:38

标签: angular angular6 angular-directive

我有一个菜单,该菜单取决于谁登录:

<mat-nav-list>
  <a mat-list-item routerLink="/login">Log-in</a>
  <a mat-list-item routerLink="/register" *hasClaim="'IsAdmin'">Register</a>
  <a mat-list-item routerLink="/about">About</a>
</mat-nav-list>

我使用指令显示或隐藏菜单项。当我未登录时,菜单项将被删除。这是对的。当我以正确的声明登录时,该指令正在报告它正在添加菜单项,但我没有看到它。

看来我的菜单没有刷新。

我的指令:

import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {AuthenticationService} from '@services/authentication.service';

@Directive({selector: '[hasClaim]'})
export class HasClaimDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private authenticationService: AuthenticationService) {
  }


  @Input() set hasClaim(claimType: any) {
    console.log('In hasClaim input. claimType:', claimType);
    if (this.authenticationService.hasClaim(claimType)) {
      console.log('Add template to DOM', this.templateRef);
      // Add template to DOM
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      console.log('Remove template from DOM');
      // Remove template from DOM
      this.viewContainer.clear();
    }
  }
}

登录之前我的控制台日志:

In hasClaim input. claimType: IsAdmin
has-claim.directive.ts:21 Remove template from DOM

登录后我的控制台日志:

login successful 
Valid token, current user is set.
Logged in.
Finished login
In canActivate. claimName: undefined
In hasClaim input. claimType: IsAdmin
Add template to DOM 

最后两行来自指令。 它确实说Add template to DOM,但是我的菜单没有更改。

似乎我丢失了一些东西。

修改: 检查元素结果:

<mat-nav-list _ngcontent-c1="" class="mat-nav-list" role="navigation">
   <a _ngcontent-c1="" class="mat-list-item" mat-list-item="" routerlink="/login" ng-reflect-router-link="/login" href="/login">
      <div class="mat-list-item-content">
         <div class="mat-list-item-ripple mat-ripple" mat-ripple="" ng-reflect-disabled="false" ng-reflect-trigger="http://localhost:4250/login"></div>
         <div class="mat-list-text"></div>
         Log-in
      </div>
   </a>
   <!--bindings={
      "ng-reflect-has-claim": "IsAdmin"
      }-->
   <a _ngcontent-c1="" class="mat-list-item" mat-list-item="" routerlink="/about" ng-reflect-router-link="/about" href="/about">
      <div class="mat-list-item-content">
         <div class="mat-list-item-ripple mat-ripple" mat-ripple="" ng-reflect-disabled="false" ng-reflect-trigger="http://localhost:4250/about"></div>
         <div class="mat-list-text"></div>
         About
      </div>
   </a>
</mat-nav-list>

<mat-nav-list>登录后未更改。

0 个答案:

没有答案