Initialize component only once when attaching to a portal
Asked Answered
P

1

6

I need to attach and detach an instance of a set of components from a portal dynamically without reinitializing it every time I attach as it degrades the performance of the application a lot.

portal = new ComponentPortal(MyComponent);
this.portalHost = new DomPortalHost(
      this.elementRef.nativeElement,
      this.componentFactoryResolver,
      this.appRef,
      this.injector
    );

const componentRef = this.portalHost.attach(this.portal);
componentRef.instance.myInput = data;
componentRef.instance.myOutput.subscribe(...);
componentRef.changeDetectorRef.detectChanges();

This is the way that is explained in this question. But every time the component is reattached it will reinitialize.

Peace answered 22/12, 2020 at 14:59 Comment(3)
Maybe you can use RouteReuseStrategy as explained in this answer: https://mcmap.net/q/1918843/-how-to-keep-the-latest-state-of-angular-componentsDrift
the most simple way is creating a module for each component and lazy loading them.Kinematograph
I am not sure if the RouteReuseStrategy will work as the component that I am rendering at a time is dynamic.Peace
S
0

I believe you'll be better off using a Component Factory in order to load components at runtime:

https://angular.io/guide/dynamic-component-loader#dynamic-component-loader

Sauer answered 28/12, 2020 at 21:3 Comment(3)
Still wouldn't I have to destroy the component every I hide it and also this is no help if I want to add a placeholder component to show when the dynamic component is not visible.Peace
Have you tried making the component singleton, and then attaching its singleton instance?Sauer
I need to attach a component dynamically so am looking for a solution where I don't have to change any implementation inside the componentPeace

© 2022 - 2024 — McMap. All rights reserved.