How to declare a directive globally for all modules?

前端 未结 2 496
温柔的废话
温柔的废话 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: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 { }
    

提交回复
热议问题