2

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

1 Answer 1

2

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

You are right. Actually we are using takeUntil in our application. What we found was that in ngOnDestroy we were missing emitting the value from notifier observable and was completing it. Emitting the notifier observable value fixed the issue. Thanks a lot. Really appreciate this. this.sub.next(null); this.sub.complete(); this.sub.unsubscribe();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.