Oregon
Oregon

Reputation: 21

Angular Elements - multiple instances share the same service by default

I've created my own webcomponent based on angular elements. I made everything according to manual.

The sample code is:

    const el = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('my-widget', el);

I have ApplicationService as well:

@Injectable({ providedIn: 'root' })
export class ApplicationService {}

After all when I run my pretty 'my-widget' element - 1 instance works well. But if I run twice it looks like the ApplicationService always run only once (singleton instance).

Example:

<my-widget id="widget1"></my-widget>
<my-widget id="widget2"></my-widget>

I want to achieve that every will have the own instance. I was looking for solution and I noticed that config has additional field like: strategyFactory in createCustomElement

{ injector: Injector; strategyFactory?: NgElementStrategyFactory; }

I am not sure how to use it. Have you any ideas?

Upvotes: 2

Views: 1164

Answers (1)

Ashish Dahiya
Ashish Dahiya

Reputation: 720

Dont' use { providedIn: 'root' }, this registers the service as a singleton at app level. If you need new instance for each component, use the providers[] of component.

@Component({
  selector: 'my-widget',
  providers: [ApplicationService]
})
export class MyWidgetComponent

Upvotes: 1

Related Questions