r/Angular2•
mrthesis

How do I avoid component from being destroyed when no longer being displayed?

Help Request

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

95
kaeh35•

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.

<div *ngIf="segmentModel">
  <!-- lineup case-->
  <div [hidden]="segmentModel !== 'lineup'">
    <app-widget type="lineup"></app-widget>
  </div>

  <!-- statistics case-->
  <div [hidden]="segmentModel !== 'statistics'">
    <app-widget type="statistics"></app-widget>
  </div>
</div>
7
nafts1•

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; }

2
TarnishedVictory•

Other options include using service or parent component for the persisted data.

3
Tsjo_Wi•

Try putting the conditions in [hidden] rather than using switch cases so that the components will only be hidden rather than removed from the DOM.

2
rattkinoid•

I don't think you can prevent it. You can set the opacity with css and that will keep it in the Dom, but its bad for performance.

Components should not have persistent functionality, that should be in service (or store)

-1