代码之家  ›  专栏  ›  技术社区  ›  BeetleJuice

角度5:重新排列动态创建的零部件

  •  8
  • BeetleJuice  · 技术社区  · 8 年前

    我使用 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 地方现在,在完成一些用户操作之后,我想对组件进行重新排序。例如,我可能希望将最后创建的组件在容器中上移一个位置。这能在角度范围内完成吗?

    public moveComponentUp(component) {
      // What to do here?  The method could also be passed the componentRef
    }
    
    1 回复  |  直到 8 年前
        1
  •  9
  •   yurzui    8 年前

    您可以使用如下方法:

    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

    推荐文章