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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With