简体   繁体   中英

Angular: How to import a module global that all other modules can access to it. (without re-importing in other modules)

I want to use an UI-Framework globally for all other modules (sub-modules from routing).

I'm using the latest versions of Angular and Material (7.2+). https://material.angular.io/

I created an Angular module that imports all Angular Material UI Modules. Imported in app.module.ts . It works fine until I change the route by loading another module. - I know why. Because every module is a separate scope. But it should be possible to import a module globally, that every component can access the UI (html).

I want to import all Mat..Modules in app.module.ts (already done) accessible also for my other modules like DashboardModule. Currently, I have to import the MaterialModules again to each Module Component (Page). Im sure / hope that this is possible. Because an UI should accessible globally to the whole page.

I think that want is not possible. The whole point of modules is to encapsulate their content, and only expose specific content via exports. The flip side of that is that if you want to use something that's exported by another module, you have to import it. There is no "global import"

That is not how Angular Modules works.

NOTE: This approach is not working, will update answer if find some solution

But there is a workaround, Creating your own Decorator to wrap NgModule decorator and use that while declaring other module.

Here is an example:

function CustomeNgModule(options: NgModule){
    options.imports = options.imports || []; 
    options.imports.push(SharedModule);
    return NgModule(options);
}

and use it as,

@CustomeNgModule({/*options*/})
export class AbcModule {
}

I have not tested my code, but it should work, let me know if it doesn't.

In case needs more information about Decorates https://www.typescriptlang.org/docs/handbook/decorators.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM