'How to reuse component in DomPortalOutlet while rendering dynamic component in Angular9?
In my angular application, I have to render dynamic components based on different situations. So whenever a new component is attached to a DomPortalOutlet instance, its working fine. For different situations different components will be rendered. That is also working. But if the same situation arrives again, I have to reuse the same component having the previous state of that component in the same portal instance. Where the target element is the same for all components. So need to render component in the same target element.
In Html,
<div #target></div>
In component .ts file,
@ViewChild('target', {static: true}) targetElement: ElementRef;
This targetElement is passed to a service where dynamic component rendering is handled.
In service,
private portalOutlet: DomPortalOutlet;
// in constructor,
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector,
private appRef: ApplicationRef,
) { }
public load(container: Element) {
this.portalOutlet = new DomPortalOutlet(
container, this.componentFactoryResolver, this.appRef, this.injector);
const portal = new ComponentPortal(this.getComponent());
this.portalOutlet.attachComponentPortal(portal);
}
public getComponent() {
// returns component based on situation
}
// also handled detaching DomPortalOutlet instance on main component destroy.
// ... other stuffs
// ...
This load method is called from the main component, where this.targetElement.nativeElement is passed.
For example, let's say for Sitation A, DynamicComponentA is rendered. And state and view of DynamicComponentA will be changed. Now, Sitation B occurs, so in that case DynamicComponentB is rendered in the same DomPortalOutlet instance. So far no problem. Now if Sitation A occurs again, then I have to render DynamicComponentA with the same state and view as before when it was rendered previously. I want to persist the state and view of DynamicComponentA if it is loaded again.
Can I achieve this? If yes, then how to do it? Or any other approach to achieve this?
Angular Version: ~9
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
