How to make directives and components available globally

穿精又带淫゛_ 提交于 2019-12-17 06:16:10

问题


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 2 application. Since this code is quite the same for each component, I thought that I would make sense to write a directive that I could define once, and use in all components. This is what my directive looks like:

import { Directive, ElementRef, HostListener, Injectable } from '@angular/core';

@Directive({
    selector: '[myCloseContentPanel]'
})

export class CloseContentPanelDirective {
    private el: HTMLElement;

    constructor(el: ElementRef) {
        this.el = el.nativeElement;
    }

    @HostListener('click') onMouseClick() {
        this.el.style.display = 'none';
    }
}

Now I expected that I could import this directive once in a app.component parent component, and that I then could use this directive throughout all the child components. This sadly doesn't work, so I would have to import this directive in each component separately. Am I doing something wrong? Or is this behaviour simply not possible?


回答1:


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.



来源:https://stackoverflow.com/questions/37560817/how-to-make-directives-and-components-available-globally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!