How to declare a directive globally for all modules?
According @CrazyMac's comment, a good way would be to create a DirectivesModule
. Inside this module you can declare and import all your directives then you will be able to import this module anywhere you want.
app/modules/directives/directives.module.ts
import { NgModule } from '@angular/core';import { HighlightDirective } from './highlight.directive';@NgModule({ imports: [], declarations: [HighlightDirective], exports: [HighlightDirective]})export class DirectivesModule { }
app/modules/directives/highLight.directive.ts
import { Directive, ElementRef } from '@angular/core';@Directive({ selector: '[myHighlight]' })export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; }}
app/modules/otherModule/other-module.module.ts
import { DirectivesModule } from '../directives/directives.module';@NgModule({ imports: [ DirectivesModule ], declarations: []})export class OtherModule { }
If you need to use the Directive
@Directive({ selector: '[appMyCommon]'})export class MyCommonDirective{}
everywhere you should create a new Module.
If you use the Angular CLI you can generate:
ng g module my-common
The Module:
@NgModule({ declarations: [MyCommonDirective], exports:[MyCommonDirective]})export class MyCommonModule{}
Important! the exports allow you to use the Directives outside the Module.
Finally, import that Module in every Module where you need to use the Directive.
for example:
@NgModule({ imports: [MyCommonModule]})export class AppModule{}
Example: Plunker