How do I avoid component from being destroyed when no longer being displayed?
I have a series of div's with a switch case, hiding them (I assume angular destroys them at this point). My custom components OnDestroy is fired when being hidden. Can I somehow prevent this? In the below example, when going from lineup to statistics, <app-widget type="lineup"> is destroyed.
<div *ngIf="segmentModel" [ngSwitch]="segmentModel">
<!-- lineup case-->
<div *ngSwitchCase="'lineup'">
<app-widget type="lineup"></app-widget>
</div>
<!-- statistics case-->
<div *ngSwitchCase="'statistics'">
<app-widget type="statistics"></app-widget>
</div>
</div>
Posted Oct 7, 2020, 6:03 AM UTC
Use [hidden] to avoid destruction, but you will have to change your ngIf and your ngSwitch as it both change the DOM
NgIf and NgSwitch does not hide element but add or remove the html element to the DOM.
Hidden can sometimes just don't work (as I often experienced) when the "display" style attribute is set elsewhere. If it doesn't work, you can add the following to your component's stylesheet:
[hidden] { display: none !important; }