将组件移动到Angular中的另一个父组件 [英] Moving a component to another parent component in Angular

查看:69
本文介绍了将组件移动到Angular中的另一个父组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是的Angular版本.

以下代码片段总结了我的第一次尝试:

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

此尝试带有以下问题:

  1. 我们不应该直接在Angular中操作DOM.通过Renderer是否可以移动组件? (回答:根据 cgTag的答案,请使用
  1. 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).
  2. If the original parent component gets destroyed after the child component was moved, the ngOnDestroy method is called on the child component.

请参见此柱塞,以演示此问题.该Plunker构建在 Angular Dynamic Component Loader示例之上.打开浏览器控制台日志,并注意已毁!"每次广告横幅更改时都会记录文本,即使是拖动我!"文本被拖到了下拉框中.

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.

推荐答案

可以使用 ViewContainerRef :

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

index是视图容器内子组件视图的索引.可以使用以下方法获得:

The index is the index of the child component's view within the view-container. That can be obtained using the following:

let index = oldParentViewContainerRef.indexOf(viewRef);

viewRef对应于子组件的视图.据我所知,如果子组件是通过

The viewRef corresponds to the view of the child component. You can only get a hold of viewRef, as far as I know, if the child component was created programmatically with the help of ComponentFactoryResolver:

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

这里的重点是,如果您希望能够在不同的父级组件之间移动组件,请确保以编程方式而不是在HTML中静态创建这些可移动组件.这为您提供了这些可移动组件的 ViewRef 实例,该实例与

The takeaway here is, if you want to be able to move components between different parent components, make sure you create those movable components programmatically, not statically in the HTML. This gives you a ViewRef instance of those movable components, which works nicely together with ViewContainerRef.

有关示例,请参见工作中的柱塞.

See working Plunker for an example.

这篇关于将组件移动到Angular中的另一个父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆