Angular 5 - load modules (that are not known at compile time) dynamically at run-time

Well, while there are complexities involved, you could try it. Depends on your code base I guess. The router exposes config property, holding its current config, and a resetConfig(routes: Routes) method for reseting configuration. You can start from there, and add, say, components on the fly.

The components do have to be reachable, though. Perhaps dynamically created, as mentioned in the other answer. Alternatively, your config could include something like this:

constructor(private router: Router) {}

private addPlugin(routePath, pluginName, pluginPath) {
    const currentConfig = this.router.config;
    currentConfig.push({
        path: routePath,
        loadChildren: `precompiled-modules/${pluginPath}#${pluginName}`,
    });
    this.router.resetConfig(currentConfig);
}

You would have to get the pluginPath and pluginName somehow - maybe calculate it by convention, maybe a lil' backend helper that gets this, maybe have the array of it preconfigured and already loaded or similar. I also assume you would have a really good test system, to make sure your plugins are "compatible". And finally, teach webpack/systemjs how to have the modules ready. All in all, it is not impossible, but it involves some groundwork.

That said, Angular 6 is around the corner, and with it, Angular Elements. Elements will provide a way to compile your modules as web components and "export" them, so that they can get used anywhere (not necessarily in Angular apps). Think jQuery plugins - there is a base jQuery.min.js you need to have loaded, but apart from that you don't think about it any more, you just use your new elements. It's similar with Angular Elements - you export what is basically a Web component. There is a "loader" part (jquery.min.js equivalent), and your Element bundle. But then your component is just another HTML node, with properties, attributes, bindings, events, you don't care any more, just like you don't about inputs.

It might be worth the wait, take a look and decide for yourself.


You could look at Dynamic Component Loading: https://angular.io/guide/dynamic-component-loader

It allows you to add components dynamically at runtime.