Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5: rearrange dynamically created components

Tags:

angular

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
}
like image 635
BeetleJuice Avatar asked Dec 20 '17 22:12

BeetleJuice


1 Answers

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

like image 191
yurzui Avatar answered Oct 08 '22 06:10

yurzui