title: Detached DOM tree memory leak
body: <p>I've discovered that my application has a memory leak, and I think it is caused by detached DOM trees. I haven't really tried to fix a memory leak before, so I have some questions.</p>
  
  <p>I've taken a heap snapshot of my app and via the class filter searched for detached:<a href="https://i.stack.imgur.com/TWVeH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TWVeH.png" alt="enter image description here"></a></p>
  
  <ol>
  <li>Some of the detached trees have 0 retained size, but when I open them, I can see elements that DO have some retained size. Should i worry about these?</li>
  </ol>
  
  <p>I have now taken 5 snapshots over some time. I have noticed some detached trees occur in all of them but with an increased retained size every snapshot, and in the latter snapshots, I get more results from the "detached" class filter. This has led me to believe that I have found the leak. I've read that nodes highlighted with yellow have direct javascript references to them, while those highlighted with red don't, but are a part of a yellow node's tree. </p>
  
  <ol start="2">
  <li>I haven't found any occurrences of yellow nodes, but I have a huge of amount of reds from my heap snapshots. How come, and how do I deal with them?</li>
  </ol>
  
  <p>I have noticed that a lot of the nodes highlighted red refer to <code>HTMLImageElements</code> from HTML code like this (I have pretty much the exact same code in 3 different HTML files):</p>
  
  <pre><code>    &lt;div class="O2-copd-flex"&gt;
        &lt;div class="O2"&gt;
          &lt;p&gt;
            &lt;img draggable="false" [matTooltip]="translations?.Tooltip.O2" (click)="toggleO2(bed)" [src]="bed.additional_O2 ? medO2 : noO2"&gt;
          &lt;/p&gt;
          ...
  </code></pre>
  
  <p>And I also have many <code>Text</code> nodes highlighted red. I inspected one of them and it said that the node's next sibling is an <code>img</code>, it's parent is a <code>p</code>, whose parent is a <code>div</code> with the class <code>O2</code>. In other words, that text should be placed between the <code>&lt;p&gt;</code> start tag and the <code>&lt;img&gt;</code> start tag in the HTML above, but as you can see, there's no text. This could be caused by the <code>matToolTip</code> though, but I'm not sure.</p>
  
  <ol start="3">
  <li>Do you have any idea why this HTML code could be causing problems? The code is created for each object in an array, and I have an update every x seconds that clears the array and adds new objects to it. So the HTML elements get removed and recreated every now and then. </li>
  </ol>
  
  <p>Any help is much appreciated. Thanks!</p>