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

8

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

9
你可以有如下方法:

方法示例:

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


移位值是什么?它是vcRef中componentRef的索引号,我们想要将其移动到哪里。例如,我想将0索引componentRef移动到1索引,因此0索引componentRef将被移动到索引1,并且需要提供的移位值为1。对吗! - WasiF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接