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.

Sachith Rukshan
  • 340
  • 6
  • 24
  • Maybe you can use `RouteReuseStrategy` as explained in this answer: https://stackoverflow.com/a/60166812/2358409 – uminder Dec 29 '20 at 07:45
  • the most simple way is creating a module for each component and lazy loading them. –  Dec 29 '20 at 14:11
  • I am not sure if the RouteReuseStrategy will work as the component that I am rendering at a time is dynamic. – Sachith Rukshan Dec 30 '20 at 01:57

1 Answers1

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

Marco Nascimento
  • 832
  • 8
  • 15
  • 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. – Sachith Rukshan Dec 30 '20 at 01:52
  • Have you tried making the component singleton, and then attaching its singleton instance? – Marco Nascimento Dec 30 '20 at 13:38
  • I need to attach a component dynamically so am looking for a solution where I don't have to change any implementation inside the component – Sachith Rukshan Dec 30 '20 at 13:52