Angular 5 - load modules (which are unknown at compile time) dynamically at runtime

Is it possible for Angular 5 to load modules / components that are not known at compile time but dynamically at run time?

I'm guessing this won't work with webpack, but perhaps with system.js?

EDIT:

The whole idea is to create a plugin based app where individual plugins are removed inside the plugin folder, Angular will automatically select it without recompiling or deploying the whole Angular app. Where plugins are separate pieces of functionality. Of course there are navigation routes etc. This means that once Angular realizes that there is a new plugin, it must add some dynamic navigation so that the user can navigate to the plugin, etc.

+3


source to share


2 answers


Well, although there are complications, you can try. Depends on your code base, I guess. The router exposes the property config

, keeping its current configuration and method resetConfig(routes: Routes)

for reseller configuration. You can start from there and add, say, components on the fly.

The components must be available. Possibly dynamically created as mentioned in another answer. Also, your config might 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 need to get the pluginPath and pluginName somehow - maybe calculate it by convention, maybe lil 'helper that gets this, maybe it's preconfigured and already loaded or similar. I also assume that you have a really good test system to keep your plugins "compatible". Finally, teach webpack / systemjs how to prepare modules. In general, this is not impossible, but it does involve some basics.

However, Angular 6 is around the corner, and with it Angular Elements. Elements will give you the ability to compile your modules as web components and "export" them so they can be used anywhere (not necessarily in Angular applications). Think jQuery plugins - there is a basic jQuery.min.js

one that you need to load, but beyond that you don't think about it anymore, you just use your new elements. It is similar to Angular Elements - you export what is basically a web component. There is a "loader" part (jquery.min.js equivalent) and your Element kit. But then your component is just another HTML node with properties, attributes, bindings, events, you don't care as much as you do not inputs.

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

+1


source


You can watch the dynamic loading of the component: https://angular.io/guide/dynamic-component-loader



It allows you to dynamically add components at runtime.

+2


source







All Articles