如何在全球范围内提供指令和组件

hY8*_*Xib 6 angular2-directives angular

我编写了一个自定义指令,我在Angular 2应用程序中使用它来关闭Angular 2应用程序的所有不同组件中的内容面板(我的模板中的一些内容持有者).由于这个代码对于每个组件都是完全相同的,我认为编写一个我可以定义一次的指令是有意义的,并且可以在所有组件中使用.这是我的指令:

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';
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我希望我可以在app.component父组件中导入一次该指令,然后我可以在所有子组件中使用该指令.遗憾的是,这不起作用,因此我必须分别在每个组件中导入此指令.难道我做错了什么?或者这种行为根本不可能?

Gün*_*uer 7

更新> = RC.5

您必须在要使用导入模块的组件,指令或管道的任何模块中导入模块.没有其他办法了.

你可以做的是创建一个模块,导出几个其他模块(例如,BrowserModule导出CommonModule.

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

@NgModule({
  imports: [AllInOneModule]
})
class MyModule {}
Run Code Online (Sandbox Code Playgroud)

这样,您可以将所有导出的内容都AllInOneModule设置为MyModule.

另请参见https://angular.io/docs/ts/latest/guide/ngmodule.html

更新<= RC.5

bootstrap(AppComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [CloseContentPanelDirective], multi: true})]);
Run Code Online (Sandbox Code Playgroud)

请参阅下面的注释 - 即使providers根组件中的每个样式指南都应该受到青睐,boostrap()但这不起作用:

原版的

在根组件上添加

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

@Component(),@Directive(),@Pipe()已包括@Injectable().也不需要在那里添加它.