angularweb-componentangular-elements

Angular WebComponent instances is getting created multiple times


I have created a webcomponent using angularElements createElement. I am using this webcomponent in different angular application.

Whenever user moves to the view which has webcomponent an instance of the webomponent is created. But when user moves in and out of the view multiple times. Multiple instances of webcomponent is getting created. and the element is available in detachedNode.

This is creating unexpected behaviour such as apis are getting triggered multiple times equal to the count of the detached elements.

Is there any way we can remove/kill the instance of the webcomponent or any way to deregister custom elements.

Any help will be highly appreciated. Thanks


Solution

  • As per the documentation:

    Angular element overview

    Custom elements bootstrap themselves - they start when they are added to the DOM, and are destroyed when removed from the DOM. Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular terms or usage conventions.


    The problem is your code is not unsubscribed on destroy of the component, try using unsubscribe or takeUntilDestroyed for all APIs in this component.

    This also applies for setTimeout, setInterval these also should be cleared when component is destroyed.

    Unsubscribe:

    private sub: Subscription = new Subscription();
    
    ngOnInit() {
      this.sub.add(this.someService.apiCall().subscribe());
    }
    
    ngOnDestroy() {
      this.sub.unsubscribe();
    }
    

    takeUntilDestroyed:

    private destroyRef = inject(DestroyRef);
    
    ngOnInit() {
      this.someService.apiCall().pipe(
        takeUntilDestroyed(this.destroyRef),
      ).subscribe();
    }