gpt4 book ai didi

Angular 5 : rearrange dynamically created components

转载 作者:太空狗 更新时间:2023-10-29 18:24:32 26 4
gpt4 key购买 nike

我使用 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
}

最佳答案

你可以有这样的方法:

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

关于 Angular 5 : rearrange dynamically created components,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47915236/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com