Home > OS >  Multiple copies of same Angular custom element on same page
Multiple copies of same Angular custom element on same page

Time:11-15

I am writing a simple custom element in Angular 13, with the usual wrapping inside another application that uses createCustomElement and then customElements.define to register it into the browser and creating a single JS bundle.

All is fine until I place 2 copies of the same custom element on the same page.

They same to share everything; for example, a simple StoreService is created only once even if the components are two.

Even worse, I am afraid that there would be conflicts with other different custom elements on the same page, say services or nrgx/store, maybe based in on the service name or the store reducer key, I don't know.

Is there a way to completely insulate a custom element written in Angular so that we can be sure it behaves fine whatever the environment it will be used is?

You can find the complete example here: enter image description here

CodePudding user response:

Thanks a lot.

Yes, providing it at the component level solves it, but I hoped there was a way to develop the custom element as usual without worrying of what is around.

I mean, that is what custom elements are all about I think, develop and bundle them without having to think where they will be used.

For example, what about ngrx/store? If I have 2 copies of the same custom element on the same page, they will share the same store, how to avoid it?

I was hoping there was a way to isolate them at a higher level, if this makes sense. Otherwise, we need to handle tens of special cases that can go wrong when the angular custom element coexists with others, and it's a nightmare.

  • Related