Search code examples
angulardirectiveangular-ng-if

Angular2 *ngIf with child directive


I can't seem to get my directive to work and wonder if it is due to the use of an *ngif.

Component HTML:

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

Directive

 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';
 }
}

The *ngIf is required in the component HTML as I am collecting data from a JSON service on ngOnInit.

Code ignored for brevity: I am adding the directive to a "shared" module which exports the Directive. This module is then imported in to the main app module.

Is this a known problem or is it my code ?

Update I got this working now however I am having to import the directive in to the module which contains the component. Can I not import it in to the AppModule and then use is globally ?


Solution

  • The Angular module system works like this:

    • You need to declare a Component/Directive/... in exactly ONE NgModule.
      You can then use it in the Components that are part of this NgModule.
    • To use a Component/Directive/... in any other NgModule, you need to export it in from the declaring NgModule and import the declaring NgModule in the NgModule where you want to use it.

    In your case you declare and export the Directive in the SharedModule and import the SharedModule in the AppModule, but you use the Directive in another NgModule, which does not import SharedModule and does not import AppModule and therefore does not know your Directive.

    So to use something in a NgModule, it needs to declare it, import the declaring NgModule or import a NgModule, which imports the declaring NgModule.
    Importing only works if the declaring NgModule exports the Directive.