Custom Element in Angular 17

778 Views Asked by At

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);
  }
}
1

There are 1 best solutions below

5
Eliseo On BEST ANSWER

See the way to create a custom Element

In your main.ts

//remove
// bootstrapApplication(AppComponent, {providers:[...]})
//   .catch((err) => console.error(err));

//and replace with:
(async () => {
  const app = createApplication({providers:[...]});
  const PopupElement = createCustomElement(AppComponent, {
    injector: (await app).injector
  });

  customElements.define('popup-element', PopupElement);

})();

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