Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make directives and components available globally

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?

like image 564
hY8vVpf3tyR57Xib Avatar asked Jun 01 '16 06:06

hY8vVpf3tyR57Xib


1 Answers

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.

like image 135
Günter Zöchbauer Avatar answered Nov 10 '22 04:11

Günter Zöchbauer