Angular 17 Universal (SSR) + Standalone components + WebComponents (Angular elements)

483 views Asked by At

It is possible to create an Angular 17 universal project with standalone components that also have web components (Angular elements)?

I'm trying to import a component (regular one) from an Angular 16 project that was created as an Angular Element (WebComponent) that allowed me to 'import' it inside an external .html file (just importing main.js, polyfills.js, runtime.js, scripts.js, and styles.css) from the Angular dist directory

Here's how I previously imported the component in an external HTML file:

<comments-widget token="token" context="main_app" rel_ext_type="deliveries" rel_ext_id="14"></comments-widget>

Initially, in the app.module, I had:

export class AppModule implements DoBootstrap {
    constructor(private injector: Injector, public globalConfig: GlobalConfigService) {}

    ngDoBootstrap(appRef: ApplicationRef) {
        if (document.querySelector('app-root')) {
            appRef.bootstrap(AppComponent);
        } else {
            // create global var here
            this.globalConfig.ExMode = true;

            // Comments
            const commentsWidget = createCustomElement(CommentsComponent, { injector: this.injector });
            customElements.define('comments-widget', commentsWidget);
        }
    }
}

I've now modified CommentsComponent to function as a standalone component in an Angular 17 SSR project, and it works fine. However, when attempting to utilize it as a WebComponent in the main.js file:

import { createApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { createCustomElement } from '@angular/elements';
import { CommentsComponent } from './app/comments/comments.component';

(async () => {
    const app = await createApplication(appConfig);

    const commentsElement = createCustomElement(CommentsComponent, { injector: app.injector });

    customElements.define('comments-widget', commentsElement);
})();

It doesn't seem to work. Any ideas on what might be causing this issue or how I could resolve it?

1

There are 1 answers

0
Dmitriy Druzhkov On

You can take some ideas from this article https://www.angulararchitects.io/en/blog/micro-frontends-with-modern-angular-part-2-multi-version-and-multi-framework-solutions-with-angular-elements-and-web-components/

  1. check if you have the right selector
  2. add globalThis.ngZone
  3. add routing processing connectRouter()