angularangular-changedetection

Angular how to swap two components inside dynamic container


I have a dynamic container that shows 2 components at a time using a paginator. I want to be able to swap a component with its previous/next and so far it's working; however, when I try to swap the first element of a page with its previous element it doesn't get rerendered (but gets swapped correctly, when I go to the previous page I can see the element swapped).

StackBlitz: https://stackblitz.com/edit/stackblitz-starters-rgvd2n


Solution

  • There seems to be a bug related to previousPageIndex, the function handlePaginator if condition, is not allowing the function to execute and hence you are not seeing the view updated.

    handlePaginator(event: PageEvent): void {
      // if (event.pageIndex === event.previousPageIndex) {
      //   return;
      // }
    
      this.paginationData.pageIndex = event.pageIndex;
    
      const start = event.pageIndex * event.pageSize;
      const end = (event.pageIndex + 1) * event.pageSize;
    
      for (const [index, element] of this.elementsRefs.entries()) {
        element.location.nativeElement.style.display =
          index >= start && index < end ? 'block' : 'none';
      }
    }
    

    On reorder, we need to trigger the handlePaginator which updates the view display property.

    reference.instance.swap.subscribe((indexDelta) => {
      const index = this.elementsRefs.indexOf(reference);
      const swapWith = index + indexDelta;
    
      if (swapWith < 0 || swapWith >= this.elementsRefs.length) {
        return;
      }
    
      [this.elementsRefs[index], this.elementsRefs[swapWith]] = [
        this.elementsRefs[swapWith],
        this.elementsRefs[index],
      ];
      this.sectionContainerRef.move(reference.hostView, swapWith);
      this.changeDetectorRef.detectChanges();
    
      this.handlePaginator({
        length: this.paginationData.length,
        pageIndex: this.paginationData.pageIndex,
        pageSize: this.paginationData.pageSize,
        previousPageIndex: undefined,
      });
    });
    

    Stackblitz Demo