This question is the Angular version of this question.
The following snippet summarizes my first attempt:
class NewParentComponent {
constructor(elRef: ElementRef) {
elRef.nativeElement.appendChild(myMovableElement);
// where the reference to myMovableElement may come from a service.
}
}
This attempt comes with the following issues:
- We are not supposed to manipulate the DOM directly in Angular. Is moving a component achievable with the
Renderer
somehow? (Ans: Per cgTag's answer, use Renderer2). - If the original parent component gets destroyed after the child component was moved, the
ngOnDestroy
method is called on the child component.
See this Plunker demonstrating the issue. This Plunker is built on top of the Angular Dynamic Component Loader example. Open the browser console log and note that the "destroyed!" text is logged every time the ad banner changes, even when the "Drag Me!" text was dragged into the drop box.