我使用ComponentFactoryResolver
动态创建组件shown in the docs。
// create a component each time this code is run
public buildComponent() {
const factory = this.componentFactoryResolver.resolveComponentFactory(MyComponent);
const componentRef = this.viewContainerRef.createComponent(factory);
const component = componentRef.instance;
this.componentArray.push(component);
}
这很有效。每次运行该函数时,都会创建一个新的MyComponent
,并将其添加到提供的ViewContainerRef
位置的DOM中。现在关注一些用户操作,我想重新排序组件。例如,我可能想要将最后创建的组件移动到容器中的一个位置。这可以在Angular中完成吗?
public moveComponentUp(component) {
// What to do here? The method could also be passed the componentRef
}
答案 0 :(得分:3)
您可以使用以下方法:
move(shift: number, componentRef: ComponentRef<any>) {
const currentIndex = this.vcRef.indexOf(componentRef.hostView);
const len = this.vcRef.length;
let destinationIndex = currentIndex + shift;
if (destinationIndex === len) {
destinationIndex = 0;
}
if (destinationIndex === -1) {
destinationIndex = len - 1;
}
this.vcRef.move(componentRef.hostView, destinationIndex);
}
将根据shift
值移动组件:
move(1, componentRef) - up
move(-1, componentRef) - down
<强> Stackblitz example 强>