title: Element doesn't get destroyed on router navigation after manipulating DOM
body: <p>I have a directive that needs to move the element on which it is applied to the body of the document:</p>
  
  <pre><code>@Directive({
    selector: '[myDirective]'
  })
  export class MyDirective implements AfterViewInit {
    constructor(private elem: ElementRef,
      private renderer: Renderer2) {
    }
  
    ngAfterViewInit() {
      // Move element to body
      this.renderer.appendChild(document.body, this.elem.nativeElement);
    }
  }
  </code></pre>
  
  <p>Now I use this directive in an element with an <code>ngIf</code> that I toggle based on some condition:</p>
  
  <pre><code>&lt;div myDirective *ngIf="visible"&gt;Test&lt;/div&gt;
  &lt;button (click)="visible = !visible"&gt;Toggle&lt;/button&gt;
  </code></pre>
  
  <p>When it runs, the div will show <em>after</em> the button as expected, because it was appended to the body. The toggle button still works at this point, and I can show/hide the div.</p>
  
  <p>The problem comes when I introduce routes:</p>
  
  <pre><code>&lt;a routerLink="/route/1"&gt;Link&lt;/a&gt;
  &lt;div myDirective *ngIf="visible"&gt;Test&lt;/div&gt;
  &lt;button (click)="visible = !visible"&gt;Toggle&lt;/button&gt;
  </code></pre>
  
  <p>Now, if I show the div, and navigate to another route, the div should get destroyed, but it's still visible! If I don't move the div to the body then it behaves as expected.</p>
  
  <p>First, I tried removing the element in <code>ngOnDestroy</code> but this doesn't work with animations, because it deletes the element <em>without</em> playing its :leave animation.</p>
  
  <p>My current workaround is to inject the router into the directive and subscribe to the first event that comes through to restore the div to its original container:</p>
  
  <pre><code>this.routerSubscription = router.events.first().subscribe(() =&gt; {
    this.renderer.appendChild(this.parentNode, this.elem.nativeElement);
  });
  </code></pre>
  
  <p>While this works, it is not great, as now the directive has a dependency in the router when it should really know nothing about it.</p>
  
  <p>How can improve on this hack to make sure the element gets destroyed properly?</p>
  
  <p><strong>DEMO:</strong> <a href="https://stackblitz.com/edit/angular-qximjw?file=app%2Fapp.component.ts" rel="noreferrer">https://stackblitz.com/edit/angular-qximjw?file=app%2Fapp.component.ts</a></p>
  
  <p>To reproduce the issue:</p>
  
  <ol>
  <li>Make sure the URL it's at the root and not within a route</li>
  <li>Click the toggle button</li>
  <li>Click the link to navigate to the route</li>
  <li>Watch the div NOT disappear</li>
  </ol>