Angular 5:重新排列动态创建的组件

问题描述 投票:3回答:1

我使用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
}
angular
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.