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

时间:2017-12-20 22:25:22

标签: angular

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

1 个答案:

答案 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