Angular2 *ngIf 与子指令

Angular2 *ngIf with child directive

我似乎无法让我的指令起作用,想知道这是否是由于使用了 *ngif。

分量HTML:

<div *ngIf="ticket" class="row">
   <div class="col-xs-12">
      <h4 appUsername>{{ticket.raisedBy.firstName}} {{ticket.raisedBy.surname}}</h4>
   </div>
</div>

指令

 import { Directive, ElementRef, Input } from '@angular/core';

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

 export class UsernameDirective {constructor(el: ElementRef) {
    console.log('App Username directive init');
    el.nativeElement.style.color = 'red';
 }
}

组件 HTML 中需要 *ngIf,因为我正在 ngOnInit 上从 JSON 服务收集数据。

为简洁起见忽略了代码:我正在将指令添加到导出指令的 "shared" 模块中。然后将此模块导入到主应用程序模块中。

这是已知问题还是我的代码?

更新 我现在可以正常工作了,但是我必须将指令导入到包含该组件的模块中。我可以不将它导入 AppModule 然后全局使用吗?

Angular 模块系统是这样工作的:

  • 您需要 declare 一个 Component/Directive/... 在一个 NgModule.
    中 然后您可以在属于此 NgModuleComponent 中使用它。
  • 要在任何其他 NgModule 中使用 Component/Directive/...,您需要 export 它来自声明 NgModuleimportNgModule 中要使用它的地方声明 NgModule

在你的情况下你 declareexport SharedModule 中的 Directiveimport [=31 中的 SharedModule =],但你在另一个 NgModule 中使用了 Directive,它没有 import SharedModule 也没有 import AppModule,因此不了解你的 Directive

所以要在 NgModule 中使用某些东西,它需要 declare 它,import 声明 NgModuleimport NgModule,其中 import 声明 NgModule
仅当声明 NgModule 导出 Directive.

时导入才有效