简体   繁体   中英

Angular 5: rearrange dynamically created components

I use the ComponentFactoryResolver to create components dynamically as 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);
}

This works well. Each time the function runs a new MyComponent is created and added to the DOM at the provided ViewContainerRef location. Now following some user action, I'd like to reorder the components. For instance I may want to move the last created component up one spot in the container. Can this be done within Angular?

public moveComponentUp(component) {
  // What to do here?  The method could also be passed the componentRef
}

You could have method like:

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);
}

that will move component depending on shift value:

move(1, componentRef) - up
move(-1, componentRef) - down 

Stackblitz example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM