How to Dynamically loading remote components using their selectors through native federation...

Discussão em 'Angular' iniciado por mideo mideo, Dezembro 18, 2024.

  1. mideo mideo

    mideo mideo Guest

    I have a micro frontend (products repo) running on port 4202. The federation configuration for this repo (federation.config.js) is as follows:

    const { withNativeFederation, shareAll } = require('@angular-architects/native-federation/config');

    module.exports = withNativeFederation({
    name: 'mfe2',
    exposes: {
    './SelectorLoaded': './src/app/selector-loaded/selector-loaded.component.ts',
    // other exposed components
    },
    // additional configuration
    });


    I want to dynamically load the SelectorLoaded component from mfe2 and use its selector directly inside a parent component in the host application. I also want to send inputs and receive outputs from the SelectorLoaded component seamlessly.

    To achieve this, I implemented the following method:

    loadMicroFrontend3() {
    loadRemoteModule('mfe2', './SelectorLoaded')
    .then((MicroModule: any) => {
    const ce = createCustomElement(MicroModule.SelectorLoadedComponent, {
    injector: this.injector,
    });

    if (!customElements.get('app-selector-loaded')) {
    customElements.define('app-selector-loaded', ce);
    }
    })
    .catch((err: any) => console.error('Error loading microfrontend:', err));
    }


    However, this approach does not work. Even though I can successfully load and render the SelectorLoaded component using a route configuration like this:

    {
    path: 'stepper',
    loadComponent: () =>
    loadRemoteModule('mfe2', './SelectorLoaded').then((m) => m.SelectorLoadedComponent),
    }


    // federation.manifest.json
    {
    "mfe1": "http://localhost:4201/remoteEntry.json",
    "mfe2": "http://localhost:4202/remoteEntry.json"
    }


    I cannot use the SelectorLoadedComponent as a selector (e.g., <app-selector-loaded></app-selector-loaded>) within a host component in the shell app.

    I was able to achieve this behavior with Module Federation, but it doesn't seem to work with Native Federation.

    My Questions:

    1. Is there a way to dynamically load and use an exposed micro frontend component with Native Federation so that I can:
      • Use its selector directly within the host app?
      • Pass inputs and listen for outputs as if it were a local Angular component?
    2. If not, what is the recommended way to achieve this functionality with Native Federation?

    Continue reading...

Compartilhe esta Página