10

I have a directive and I want to use it in multiple modules. Declaring it on each modules produces an error. Thus, I tried to declare it in a shared module and import this shared module to other modules. However, it didn't work. It only works when it is declared exactly on the component's own module.

Here is my SharedModule:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { GeneralDataService } from './general-data.service';
import {ModalDirective} from '../directives/modal.directive';

    @NgModule({
      imports: [
        CommonModule
      ],
      providers: [GeneralDataService],
      declarations: [ModalDirective]
    })
    export class SharedModule { }

And the module that I want to use ModalDirective:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './patient.component';
import {SharedModule} from '../shared/shared.module';
@NgModule({
  imports: [
    CommonModule,
    SharedModule
  ],
  providers: [  ],
  declarations: [ MyComponent ]
})
export class MyModule { }

In MyComponent component:

export class MyComponent implements OnInit, AfterViewInit {

  @ViewChild(ModalDirective) modal: ModalDirective;

  ...
}

modal in MyComponent is undefined (even in ngAfterViewInit) if ModalDirective is not declared in MyModule. Anyone knows how to fix this?

Bünyamin Sarıgül
  • 3,031
  • 4
  • 30
  • 55

1 Answers1

15

In your SharedModule you need to export the ModalDirective

...

@NgModule{(
   ...
   exports: [ModalDirective]
)}
export class SharedModule { ... }

See docs on shared modules for more info

Fredrik Lundin
  • 8,006
  • 1
  • 29
  • 35
  • Thx Fredrik! My directive has an injection of `TemplateRef`. However when I add the directive into the `NgModule.exports` list, I got an error says `No provider for TemplateRef!`. Any ideas? – Cosmo Aug 13 '17 at 11:11
  • @cosmozhang - can't really tell without seeing your code, but have a look at this thread: https://stackoverflow.com/questions/35932074/angular2-no-provider-for-templateref-ngif-templateref – Fredrik Lundin Aug 14 '17 at 07:45
  • 3
    For me it doesn't work even after adding it to exports – Himanshu Arora Sep 27 '18 at 04:46