使用指令时出现Angular 4错误

时间:2017-09-01 00:36:40

标签: javascript angular angularjs-directive header

我有以下指令声明:

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

import { UserService } from './services/user.service';

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

      condition: boolean;
      constructor(
        private templateRef: TemplateRef<any>,
        private userService: UserService,
        private viewContainer: ViewContainerRef
      ) {}
      ngOnInit() {
        this.userService.isAuthenticated.subscribe(
          (isAuthenticated) => {
            if (isAuthenticated && this.condition || !isAuthenticated && !this.condition) {
              this.viewContainer.createEmbeddedView(this.templateRef);
            } else {
              this.viewContainer.clear();
            }
          }
        );
      }

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

我已经在我的NgModule的声明中定义了它,如下所示:

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { ListErrorsComponent } from './list-errors.component';
import { ShowAuthedDirective } from './show-authed.directive';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    RouterModule
  ],
  declarations: [
    ListErrorsComponent,
    ShowAuthedDirective,
  ],
  exports: [
    CommonModule,
    FormsModule,
    ListErrorsComponent,
    ReactiveFormsModule,
    HttpModule,
    RouterModule,
    ShowAuthedDirective
  ]
})
export class SharedModule {}

但是当我在我的html组件中使用它时如下:

<nav class="navbar navbar-light">
  <div class="container">
    <a class="navbar-brand" routerLink="/">plant-simulator</a>

    <!-- Show this for logged out users -->
    <ul *appShowAuthed="false"
        class="nav navbar-nav pull-xs-right">

      <li class="nav-item">
        <a class="nav-link"
          routerLink="/register"
          routerLinkActive="active">
          Sign Up
        </a>
      </li>

    </ul>
    <ul *appShowAuthed="true"
        class="nav navbar-nav pull-xs-right">
      <!-- Show this for logged in users -->
      <li class="nav-item">
        <a class="nav-link"
          [routerLink]="['/profile', currentUser.id]"
          routerLinkActive="active">
          <img [src]="currentUser.image" *ngIf="currentUser.image" class="user-pic" />
          {{ currentUser.email }}
        </a>
      </li>
    </ul>

  </div>
</nav>

我遇到了一些错误,如下面的屏幕截图所示:

enter image description here

有关为什么抱怨解析的任何线索?

1 个答案:

答案 0 :(得分:0)

我必须重命名该指令以匹配类声明:

@Directive({ selector: '[showAuthed]' })

请注意,选择器现在与ShowAuthedDirective类的名称相匹配