带有子指令的Angular2 * ngIf

时间:2017-03-03 09:44:27

标签: angular directive ngif

我似乎无法让我的指示工作,并想知道是否是由于使用了* 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';
 }
}

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

为简洁而忽略了代码:我将指令添加到&#34;共享&#34;导出指令的模块。然后将此模块导入主应用程序模块。

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

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

1 个答案:

答案 0 :(得分:0)

Angular模块系统的工作原理如下:

  • 您需要declare Component / Directive / ...只需一NgModule
    然后,您可以在Component的{​​{1}}中使用它。
  • 要在任何其他NgModule中使用Component / Directive / ...,您需要NgModule声明exportNgModule {1}}在您要使用它的import中声明NgModule

在您的情况下,您NgModuledeclare export中的Directive以及SharedModule import SharedModule ,但您使用的是其他AppModule中的DirectiveNgModule import而非SharedModule import,因此不知道您的AppModule Directive

所以要在NgModule中使用某些内容,需要declareimport声明NgModuleimport a NgModule,其中import声明NgModule 仅当声明NgModule导出Directive

时,导入才有效