角度5:动态组件的交换位置

Was*_*siF 12 typescript angular angular5

我想在视图中交换动态放置的组件的位置.

即我已经动态创建了id = 1和2的组件,如图所示.

在此输入图像描述

现在我需要交换两个组件的位置但是如何?

我知道的一件事(只有理论上)是位置可以通过ViewContainerRef classvia对象内部的移动方法来改变viewContainerRef.move(componentRef.hostView, index).

我尝试了但是位置没有互换.

@ViewChild(ContainerRefDirective) location: ContainerRefDirective;

let componentFactory = this.factoryResolver.resolveComponentFactory(EntryComponent);
let componentRef = this.location.viewContainerRef.createComponent(componentFactory);

let entryComponent: EntryComponent = componentRef.instance;
// lets say counter is variable that increments its value on new component creation.
entryComponent.Id = ++counter; 

// move method is being called right after a new component is created and placed. 
//this piece of code is in the same method (that is creating the dynamic components)
this.location.viewContainerRef.move(componentRef.hostView, 1);
Run Code Online (Sandbox Code Playgroud)

我已经阅读了有关angular.io的ViewContainerRef文档,并阅读了有关此问题的几乎相同的问题,但无法理解或解决此问题.

For*_*stG 11

为什么不将两个动态组件绑定到数组?例如,如果您有"objectA"和"objectB":

this.renderArray.push(objectA);
..
this.renderArray.push(objectB);
Run Code Online (Sandbox Code Playgroud)

你的HTML看起来像这样:

<ng-container *ngFor="let renderObject of renderArray">
   <<you can reference objectA and objectB by using "renderObject.value" etc.>>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

当你需要交换它们的位置时,你只需要操纵数组,而角度就可以完成剩下的工作:

this.renderArray = this.renderArray.reverse();
Run Code Online (Sandbox Code Playgroud)

它将以新的顺序重新呈现ngFor容器.见这里工作的例子.

  • 为什么需要处理控件类中的组件引用?如果可能的话,你应该设法让角度渲染引擎处理它.只关注数据,并相应地绑定.因此,不是绑定组件,而是绑定数据,即组件_.(如果您使用的是动态组件绑定,那么恐怕我的方法无法使用) (2认同)

Was*_*siF 6

解决了这个问题.

我做了什么?

我更改了值,而不是交换组件的位置

即我替换了值1 <=> 2,看起来组件是互换的.

怎么样?

// array to hold the newly created component instances
entryComponents: EntryComponent[] = new Array<EntryComponent>();
Run Code Online (Sandbox Code Playgroud)

然后将新创建的组件推送到该数组中

let factoryResolver = this.factoryResolver.resolveComponentFactory(EntryComponent);    
let componentRef = this.location.viewContainerRef.createComponent(factoryResolver);

this.entryComponents.push(componentRef.instance); // getting components' instances
Run Code Online (Sandbox Code Playgroud)

现在交换值,使组件看起来像互换.

感谢@ForestG,提出这个建议