【问题标题】:How to make directives and components available globally如何使指令和组件在全球范围内可用
【发布时间】:2016-09-30 08:36:15
【问题描述】:

我编写了一个自定义指令,在我的 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 父组件中导入该指令一次,然后我可以在所有子组件中使用该指令。遗憾的是,这不起作用,所以我必须分别在每个组件中导入这个指令。难道我做错了什么?或者这种行为根本不可能?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    更新 >=RC.5

    您必须在要使用导入模块的组件、指令或管道的任何模块中导入模块。没有办法解决。

    您可以做的是创建一个导出多个其他模块的模块(例如,导出CommonModuleBrowserModule

    @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

    更新

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

    请参阅下面的 cmets - 即使根组件中的每个样式指南 providers 应该优先于 boostrap() 这不起作用:

    原创

    在根组件上添加

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

    @Component()@Directive()@Pipe() 已经包含@Injectable()。也不需要在那里添加它。

    【讨论】:

    • 谢谢!当我将它添加到我的应用程序的引导文件中时,答案有效,而不是当我将它添加到根组件中时。据我了解,将其添加到引导文件中并不是最佳做法,您知道这可能是什么吗?
    • 其实我自己还没有在组件的providers: [...]中尝试过。我以这种方式发布代码是因为样式指南不鼓励使用bootstrap()。您可以尝试将其添加到 directives: []
    • 指令和提供者对我不起作用,引导程序起作用。如果您在回答中提到这一点,我会接受!
    • 任何想法如何在最新版本的 Angular2 中完成?只是在主模块中声明它似乎并没有解决问题,并且提供和 PLATFORM_DIRECTIVES 似乎被贬低了。
    • 你确实很快!非常感谢!
    猜你喜欢
    • 2021-09-07
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多