Moving a component to another parent component in Angular

This question is an 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 has the following problems:

  • We should not manipulate the DOM directly in Angular. Does the component reachable using Renderersomehow? (Ans: Per cgTag answer , use Renderer2 ).
  • If the original parent component is destroyed after moving the child component, the method ngOnDestroyis called on the child component.

Plunker, . Plunker Angular . , "!" , , "Drag Me!" .

+4
3

ViewContainerRef:

oldParentViewContainerRef.detach(index);
newParentViewContainerRef.insert(viewRef);

index - view. , :

let index = oldParentViewContainerRef.indexOf(viewRef);

viewRef . , viewRef, ComponentFactoryResolver:

let factory = componentFactoryResolver.resolveComponentFactory(MyChildComponentType);
let componentRef = oldParentViewContainerRef.createComponent(factory);
let viewRef = componentRef.hostView;

, , , , HTML. ViewRef , ViewContainerRef.

Plunker .

+5

, Renderer2, . - Angular Universal.

Angular DOM, AngularJS. Angular ViewRef, DOM. , , ViewRef, , .

Renderer2 API. , .

abstract appendChild(parent: any, newChild: any): void;
abstract insertBefore(parent: any, newChild: any, refChild: any): void;
abstract removeChild(parent: any, oldChild: any): void;

, Windows. . - DOM .

- . , , . , ngOnDestroy, DOM .

+3

DOM , . , DOM (, ). , DOM angular DOM , .

When moving a component to the DOM, it was very useful for me to move it inside the wrapper. For example, when I include components in a modal component, the modal parent is in the DOM nested at the component add level, and the modal children are added to the body tag. When the modality is to be closed, the children of the dialog are added back to the shell, returning the component back to the shell with them.

0
source

Source: https://habr.com/ru/post/1681313/


All Articles