How to make directives and components available globally

后端 未结 1 433
误落风尘
误落风尘 2020-11-28 15:09

I wrote a custom directive that I use in my Angular 2 application to close content panels (some content holders in my template) in all the different components of my Angular

相关标签:
1条回答
  • 2020-11-28 16:00

    update >=RC.5

    You have to import a module in whatever module you want to use components, directives or pipes of the imported module. There is no way around it.

    What you can do is to create a module that exports several other modules (for instance, the BrowserModule that exports CommonModule.

    @NgModule({
      declarations: [CoolComponent, CoolDirective, CoolPipe],
      imports: [MySharedModule1, MySharedModule2],
      exports: [MySharedModule1, MySharedModule2, CoolComponent, CoolDirective, CoolPipe],
    })
    export class AllInOneModule {}
    
    @NgModule({
      imports: [AllInOneModule]
    })
    class MyModule {}
    

    This way you make everything exported by AllInOneModule available to MyModule.

    See also https://angular.io/docs/ts/latest/guide/ngmodule.html

    update <=RC.5

    bootstrap(AppComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [CloseContentPanelDirective], multi: true})]);
    

    See comments below - even though per style guide providers in the root component should be favored over boostrap() this doesn't work:

    original

    On the root component add

    @Component({
      selector: 'my-app',
      providers: [provide(PLATFORM_DIRECTIVES, {useValue: [CloseContentPanelDirective], multi: true})],
      templat: `...`
    })
    export component AppComponent {
    }
    

    @Component(), @Directive(), @Pipe() already include @Injectable(). No need to add it there as well.

    0 讨论(0)
提交回复
热议问题