Strange behavior using Angular elements with application builder v19

Discussão em 'Angular' iniciado por billyjov, Janeiro 28, 2025.

  1. billyjov

    billyjov Guest

    i built a demo app where i use the @angular/elements package in v19 to build a mfe-1 app as web component and display this inside another app named shell. Both apps uses the application builder.

    Both apps are inside an Nx monorepo to simplify the workflow.

    A litle bit about my setup:

    1. APP one mfe-1 just display a simple text. It use a standalone component setup.

    I changed the boostrap process to make a web component from the app.

    The main.ts looks like this:

    import { createCustomElement } from '@angular/elements';
    import {
    createApplication
    } from '@angular/platform-browser';

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

    (async () => {
    const appRef = await createApplication(appConfig);
    const appComponent = createCustomElement(AppComponent, {
    injector: appRef.injector,
    });

    customElements.define('nds-mfe-1', appComponent);
    })();


    everything else is standard to angular apps in the new standalone style.

    i adjusted the build process to not hashing the build output, so that i can easily integrate the main.js file in another app.

    1. APP two is a shell app, that should be used to display nds-mfe-1 element. Shell also doesnt have many content and simply have a placeholder from the generated app.

    i wrote a simple service to integrate the main.js script as module into the page, so that i can render my element.

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

    @Injectable({
    providedIn: 'root',
    })
    export class MicroFrontendLoaderService {
    private loaded = false;

    loadScript(url: string): Promise<void> {
    return new Promise((resolve, reject) => {
    if (this.loaded) {
    resolve();
    return;
    }

    const script = document.createElement('script');
    script.src = url;
    script.type = 'module';
    script.onload = () => {
    this.loaded = true;
    resolve();
    };
    script.onerror = () => {
    reject(new Error(`Failed to load script: ${url}`));
    };
    document.body.appendChild(script);
    });
    }
    }


    As soon as i call the script inside my component, the component is rendered twice. This make my main.js appear twice in the DOM as script tag. My web components does not appear on the page.

    Here is the full reproduction of my issue on github.. Just run npm install and then nx serve shell to start the setup.

    Can someone explain why i get this behavior?

    Continue reading...

Compartilhe esta Página