How to expand all rows by default in material table?

Viewed 1861
2 Answers

If you want to keep the same logic with only having one row collapsable at once, but having them all start as expanded, you can just change

[@detailExpand]="row.element == expandedElement ? 'expanded' : 'collapsed'"

To

[@detailExpand]="row.element != expandedElement ? 'expanded' : 'collapsed'"

If you want a fully functional table with expand/collapsable elements, you could add a new property called 'expanded' to your Element interface:

export interface Element {
  name: string;
  position: number;
  weight: number;
  symbol: string;
  expanded: boolean;
}

You can then add a default value of true to your new property in the datasource:

const data: Element[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H', expanded: true },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He', expanded: true  }
 ...
];

Lastly, change your row logic to use the expanded property instead of selected element:

Change:

[class.expanded]="expandedElement == row"
(click)="expandedElement = row"
...
[@detailExpand]="row.element == expandedElement ? 'expanded' : 'collapsed'"

To:

[class.expanded]="row.expanded"
(click)="row.expanded = !row.expanded"
...
[@detailExpand]="row.element.expanded ? 'expanded' : 'collapsed'"

Don't forget to clear away the unused code!

Related