[英]Angular 5: rearrange dynamically created components
我使用ComponentFactoryResolver
动态创建组件, 如文档中所示 。
// 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.