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?
Put a debugger; statement inside the constructor of your directive. Then you'll know for sure when it's working and you can remove it. Make sure you have selector: '[magicFeature]' and not selector: 'magicFeature' Sometimes you need to restart your ng serve to make sure everything is refreshed.
Sharing moduleslink You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Notice the following: It imports the CommonModule because the module's component needs common directives.
Directivelink. Decorator that marks a class as an Angular directive. You can define your own directives to attach custom behavior to elements in the DOM.
In your SharedModule
you need to export
the ModalDirective
...
@NgModule{(
...
exports: [ModalDirective]
)}
export class SharedModule { ... }
See docs on shared modules for more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With