I am facing a challenge with dynamically placing components inside the view and need to switch their positions.
For instance, I have dynamically created components with ids 1 and 2, as shown in the figure linked below.
https://i.sstatic.net/hgxd2.jpg
Now, the task at hand is to swap the positions of these two components. But how can this be achieved?
Theoretically, I know that the location can be altered using the 'move' method within the ViewContainerRef
class through an object like so:
viewContainerRef.move(componentRef.hostView, index)
.
I attempted to implement this method but unfortunately, the positions did not actually swap.
@ViewChild(ContainerRefDirective) location: ContainerRefDirective;
let componentFactory = this.factoryResolver.resolveComponentFactory(EntryComponent);
let componentRef = this.location.viewContainerRef.createComponent(componentFactory);
let entryComponent: EntryComponent = componentRef.instance;
// Assuming the counter variable increments with each new component creation.
entryComponent.Id = ++counter;
// The move method is invoked immediately after creating and placing a new component.
// This snippet of code resides within the same method responsible for dynamic component creation.
this.location.viewContainerRef.move(componentRef.hostView, 1);
I have thoroughly reviewed the documentation on ViewContainerRef provided on angular.io and also looked into similar questions related to this matter. However, I seem to be struggling to comprehend or resolve this issue.