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?
In your SharedModule
you need to export
the ModalDirective
...
@NgModule{(
...
exports: [ModalDirective]
)}
export class SharedModule { ... }
See docs on shared modules for more info