Search code examples
angularangular-materialangular-material-table

Angular (7+) Material table with expandable rows - multiple expanded rows at the same time


I am using Material table with expandable row

I would like to have multiple rows expanded on row clicks. The default behavior is to close the previously expanded row upon a new row click. I don't want the previous ones to be closed, each should be left open until clicked again. How can I do this?


Solution

  • Here is another approach.

    Simply make the variable an array

    expandedElement: PeriodicElement[] = [];
    

    On the animation section use a function instead of direct checking

    [@detailExpand]="checkExpanded(element) ? 'expanded' : 'collapsed'"
    

    And use the same function while adding the class

    [class.example-expanded-row]="checkExpanded(element)"
    

    And on click make a function call. If the element is present remove it from the array and if not present add it

    (click)="pushPopElement(element)"
    

    And here are the 2 functions which are used. Please feel free to improve efficiency of the methods. Its a crude method written in a short time for the demo.

    checkExpanded(element): boolean {
        let flag = false;
        this.expandedElement.forEach(e => {
          if(e === element) {
            flag = true;
    
          }
        });
        return flag;
      }
    
      pushPopElement(element) {
        const index = this.expandedElement.indexOf(element);
        console.log(index);
        if(index === -1) {
            this.expandedElement.push(element);
        } else {
          this.expandedElement.splice(index,1);
        }
      }
    

    You can find the working sample here : https://stackblitz.com/edit/angular-x6jz81