首页 > 解决方案 > 为什么我的客户指令不起作用?

问题描述

我的主要目的是使用客户指令来显示不同的页面取决于用户登录或注销

    <!-- Show this for logged out users -->
    <ul *appShowAuthed="false"
        class="nav navbar-nav pull-xs-right">
        <li class="nav-
        <li class="nav-item">
            <a class="nav-link" routerLink="/register" routerLinkActive="active">
                Sign up
            </a>
        </li>
    </ul>
  <!-- Show this for logged out users -->
    <ul *appShowAuthed="true"
        class="nav navbar-nav pull-xs-right">
        <li class="nav-item">
            <a 
                class="nav-link" 
                routerLink="/"
                routerLinkActive="active"
                [routerLinkActiveOptions]="{ exact: true }">
            </a>
        </li>
    </ul>

我的客户指令

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

@Directive({
  selector: '[appShowAuthed]'
})
export class ShowAuthedDirective implements OnInit {

  constructor(
    private templateRef: TemplateRef<any>,
    private userService: UserService,
    private viewContainerRef: ViewContainerRef
  ) {}

  condition: boolean;

  ngOnInit() {
    this.userService.isAuthenciated.subscribe(
      (isAuthenticated) => {
        if (isAuthenticated && this.condition || !isAuthenticated && !this.condition) {
          this.viewContainerRef.createEmbeddedView(this.templateRef);
        } else {
          this.viewContainerRef.clear();
        }
      }
    );
  }

  @Input() set appShowAuthed(condition: boolean) {
    this.condition = condition;
  }

}

我在我的头模块中导入它

import { ShowAuthedDirective } from './../show-authed.directive';
import { NgModule } from '@angular/core';


@NgModule({
    declarations: [
        HeaderComponent,
        ShowAuthedDirective
    ],

    imports: [],
    providers: []
})

export class headerModule {}

但是当我启动它时,在谷歌浏览器中它显示:core.js:7813 无法绑定到“appShowAuthed”,因为它不是“ul”的已知属性

标签: angularangular-cliangular-directive

解决方案


您应该CommonModule在您的导入数组下headerModule

import { ShowAuthedDirective } from './../show-authed.directive';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

@NgModule({
    declarations: [
        HeaderComponent,
        ShowAuthedDirective
    ],

    imports: [ CommonModule ],
    providers: []
})

export class headerModule {}

更新

HTML 上有一个*前缀。它应该被删除


推荐阅读