Angular `NG0203 Error` for `StandAloneInjector` on trying to embed custom element into view...

Discussão em 'Angular' iniciado por Dalantren, Fevereiro 28, 2025.

  1. Dalantren

    Dalantren Guest

    Details: I have two completely separate Angular applications. One is like parent one and other one is child. Child should be exported as js module, loaded by parent app and embedded into some container. But important thing is that I'd wish to have an injection context of parent application inside child one. What I'm trying to do is just build child application as a js module (exporting entry component and config), in parent app add a script-element on my page, load it, and on load take exported component and config and create child app using createCustomElement from @angular/elements. And it works fine, no errors. But when I'm trying to render this component in some container - angular throws an error NG0203 can't call 'inject()' out of InjectionContext. It's because on component initialization angular created it's own StandaloneInjector and calls inject() inside. What am I doing wrong here?

    Source code: https://github.com/Dalantren/embedded-component

    Tried also to use createApplication() before creating custom element and runInInjectionContext() - didn't help

    Angular version 18.2, but tested on latest 19.2 - it has same issue

    Piece of source code of parent app:

    private container = viewChild('customSelectorContainer', { read: ViewContainerRef });

    ngOnInit() {
    this.loadScript().then(() => {
    const childElement: HTMLElement = this.renderer.createElement('child-app');

    // Here comes an error
    this.container()?.element.nativeElement.appendChild(childElement);
    });
    }

    private loadScript(): Promise<void> {
    const src = 'http://127.0.0.1:5500/dist/child/main.js';
    return new Promise((resolve, reject) => {
    const scriptElement = document.createElement('script');
    scriptElement.src = src;
    scriptElement.type = 'module';
    scriptElement.onload = () => {
    import(/* @vite-ignore */ src)
    .then(({ emConfig, emComponent }) => {
    const customElement = createCustomElement(emComponent, { injector: this.envInjector });
    customElements.define('child-app', customElement);
    resolve();
    })
    }
    document.body.appendChild(scriptElement);
    });

    Continue reading...

Compartilhe esta Página