【问题标题】:Angular 5: rearrange dynamically created componentsAngular 5:重新排列动态创建的组件
【发布时间】:2018-06-03 13:21:51
【问题描述】:

我使用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】:

    你可以有这样的方法:

    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将是我需要提供的移位值?对!!!
    猜你喜欢
    • 1970-01-01
    • 2019-11-13
    • 2018-10-29
    • 2020-06-03
    • 2017-09-10
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多