angularweb-componentangular-elementsangular17

Custom Element in Angular 17


since I updated Angular to version 17 I can't create web components.. I used to do it in app.module, where are they created now? I tried in app.component as the guide says but it doesn't seem to work.. Can someone help me please??

I tried in app.component as the guide says but it doesn't seem to work..

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
    <input #input value="Message" />
    <button type="button" (click)="popup.showAsElement(input.value)">Show as element</button>
  `,
  providers: [PopupService],
  imports: [PopupComponent],
})
export class AppComponent {
  constructor(
    injector: Injector,
    public popup: PopupService,
  ) {
    // Convert `PopupComponent` to a custom element.
    const PopupElement = createCustomElement(PopupComponent, {injector});
    // Register the custom element with the browser.
    customElements.define('popup-element', PopupElement);
  }
}

Solution

  • See the way to create a custom Element. For the purposes of this example

    In your main.ts replace

    bootstrapApplication(AppComponent, appConfig)
    .catch((err) => console.error(err));
    

    with

    createApplication()
    .then((app) => {
        const app = createApplication({providers:[...]});
        const PopupElement = createCustomElement(AppComponent, {
            injector: (app).injector
        });
        customElements.define('popup-element', PopupElement);
    }
    .catch((err) => console.error(err));
    

    a stackblitz (see that, you need refresh the "visor" if you make any change)

    however, this can be simplified further without removing the bootstrapApplication method:

    bootstrapApplication(AppComponent, appConfig)
    .then((app) => {
        const PopupElement = createCustomElement(AppComponent, {
            injector: (app).injector
        });
        customElements.define('popup-element', PopupElement);
    })
    .catch((err) => console.error(err));