我编写了一个自定义指令,在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';
}
}
现在,我希望可以一次在app.component父组件中导入此指令,然后可以在所有子组件中使用此指令。遗憾的是,这行不通,因此我必须在每个组件中分别导入此指令。难道我做错了什么?还是这种行为根本不可能?
更新> = 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 {}
这样,您就可以将导出的所有内容AllInOneModule
提供给MyModule
。
另请参阅https://angular.io/docs/ts/latest/guide/ngmodule.html
更新<= RC.5
bootstrap(AppComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [CloseContentPanelDirective], multi: true})]);
请参阅下面的注释-尽管providers
应该优先使用根组件中的每个样式指南,但boostrap()
这样做不起作用:
原版的
在根组件上添加
@Component({
selector: 'my-app',
providers: [provide(PLATFORM_DIRECTIVES, {useValue: [CloseContentPanelDirective], multi: true})],
templat: `...`
})
export component AppComponent {
}
@Component()
,@Directive()
,@Pipe()
已包括@Injectable()
。也无需在此添加它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句