4

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?

Efron A.
  • 353
  • 3
  • 10
  • 19

2 Answers2

7

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

4

For achieving this, you have to add one more properties in the data source like expanded:true, and then change on row click , toggle this property in the data source, and based on this property change the class in the HTML for expansion.

Working Demo

Added code snippet in case link breaks.

const ELEMENT_DATA: PeriodicElement[] = [
  {
    ...
    expanded: false
  },
  {
    ...
    expanded: false
  }
]

On click of the row, simply toggle expanded property (Loop is not required), also add class based on the same expanded property.

<div class="example-element-detail"
           [@detailExpand]="element.expanded ? 'expanded' : 'collapsed'">
...
</div>

<tr mat-row *matRowDef="let element; columns: columnsToDisplay;"
      [class.example-expanded-row]="element.expanded"
      (click)="element.expanded = !element.expanded">
</tr>
Sameer
  • 4,758
  • 3
  • 20
  • 41
akpgp
  • 761
  • 6
  • 10