Make Module global available in Angular application

放肆的年华 提交于 2020-01-16 15:41:33

问题


I have the following Module which components I use on other modules:

import { NgModule } from '@angular/core';

import { CommonModule } from '@angular/common';  
import { ClickOutsideModule } from "ng-click-outside";

import { PopupComponent} from './popup.component';

@NgModule({  
  declarations: [
    PopupComponent
  ],      
  imports: [
    CommonModule,
    ClickOutsideModule
  ],  
  exports: [
    PopupComponent
  ],
  providers: []
})

export class PopupModule {}

And I have my AppModule:

import { NgModule } from '@angular/core';

import { AppBrowserModule } from './app-browser.module';
import { AppRoutingModule } from './app-routing.module';

import { HomeModule } from './home/home.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppBrowserModule,  
    HomeModule,
    AppRoutingModule
  ],
  exports: [],
  bootstrap: [ AppComponent ]
})

export class AppModule { }
  1. Is it possible to have ClickOutsideModule available in all App modules, such as PopupModule, without the need to import it in every module?

    Or do I always need to import it in each module it uses it?

  2. What is Exports in AppModule for?


回答1:


Just create a SharedModule, add the ClickOutsideModule to the imports and exports array of it. Something like this:

import { NgModule } from '@angular/core';
import { ClickOutsideModule } from "ng-click-outside";

@NgModule({ 
  imports: [
    ClickOutsideModule,
    ...
  ],  
  exports: [
    ClickOutsideModule,
    ...
  ],
})
export class SharedModule {}

And then import the SharedModule whereever you want to have access to the ClickOutsideModule module. Say for eg, if you want it in the AppModule, here's how you'll do it:

...
import { SharedModule } from './shared/shared.module';

@NgModule({
  ...,
  imports: [
    SharedModule,
    ...
  ],
  ...
})

export class AppModule { }

You can do the same for PopupModule:

...
import { SharedModule } from './shared/shared.module';

@NgModule({
  ...,
  imports: [
    SharedModule,
    ...
  ],
  ...
})

export class PopupModule { }


来源:https://stackoverflow.com/questions/53885076/make-module-global-available-in-angular-application

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