How to declare a directive globally for all modules?

前端 未结 2 497
温柔的废话
温柔的废话 2020-12-13 13:34

I\'m developing a Github repo which follows the offical tutorial of Angular (Tour of Heroes). You can see all the code here.

My problem, is that I have a directive d

相关标签:
2条回答
  • 2020-12-13 13:58

    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

    0 讨论(0)
  • 2020-12-13 13:59

    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 { }
    
    0 讨论(0)
提交回复
热议问题