Home > Software design >  How can I Collapse/Expand Multiple Divs in ngx-virtual-scroll?
How can I Collapse/Expand Multiple Divs in ngx-virtual-scroll?

Time:12-07

https://stackblitz.com/edit/angular-ngx-virtual-scroller-byykpn

Here is what I have done so far, now I need to Expand/Collapse all divs which is after the group header.

CodePudding user response:

You could wrap those divs in an ng-container with ngIf and toggle expansion. I just considered you have a unique id for each item. So we can just use it to mark which item is expanded. In case you do not have a unique key for each item, you could just use the index of the item.

Your Template:

<button (click)="toggleExpand(item.id)">expand</button>

  <ng-container *ngIf="item.id == isExpanded">
          <div >Question1</div>
        <div >Question2</div>
        <div >Question3</div>
        <div >Question4</div>
        <div >Question5</div>
  </ng-container>

The toggle method:

toggleExpand(val) {
    this.isExpanded= val == this.isExpanded? '' : val;
  }

If you want to expand more than one row in the same time, then you should memorize the expanded rows in an object isCollapsed where the key is the expanded item.id and the value is a boolean e.g.

  isExpanded = {};

  toggleExpand(val) {
    this.isExpanded[val] = !this.isExpanded[val];
  }

And adjust your ng-container to:

<ng-container *ngIf="isExpanded[item.name]">

CodePudding user response:

You only need to have a boolean array for mapping collapsed divs.

See your code working HERE

https://stackblitz.com/edit/angular-ngx-virtual-scroller-nzqnbw?file=src/app/app.component.html

isCollapsed: boolean[] = [];

  constructor(private cd: ChangeDetectorRef) {
    for (let i = 1; i < 10; i  ) {
      this.items.push({ name: 'Item '   i });
      this.isCollapsed[i] = true;
    }

    // Just to see the first item not collapsed, you can omit it if you want them all collapsed by default.
       if (this.items.length > 0) { this.isCollapsed[0] = false; }
  }

HTML:

 <div
        *ngFor="let item of scroll.viewPortItems; let indexOfColaps = index"
        
      >

<div *ngIf="!isCollapsed[indexOfColaps]">
          <div >Question1</div>
          <div >Question2</div>
          <div >Question3</div>
          <div >Question4</div>
          <div >Question5</div>
</div>

\\You can change div *ngIf="... for container *ngIf="... if you want.

  • Related