我想交换视图中动态放置组件的位置。
即,我已经创建了具有id = 1和2的动态组件,如图所示。
现在,我需要交换两个组件的位置,但是怎么做呢?
唯一知道(理论上)的事情是,可以通过ViewContainerRef class
中的move方法通过对象更改位置,例如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);
我已经阅读了关于angular.io中的ViewContainerRef文档并且阅读了几乎相同的问题,但是仍然无法理解或解决此问题。
ViewContainerRef.move(ref, index)
方法无法交换动态组件的位置。如果可以,那么如何实现? - WasiF