CAlex
CAlex

Reputation: 1140

Expand Angular Material expansion table row via TypeScript

I am using an Angular Material expansion datatable that I modified from the docs, here. I refresh the data in the table when a change is made. This works fine, but the table fully collapses to its default state after the refresh, creating an undesirable user experience.

I would like to force the previously open row to expand after the refresh. I have yet to find anyway to forcefully expand the rows from TypeScript. Below is my method that gets called when a table refresh occurs:

  refresh() {
    this.refreshDatatable();
    // I want to forcefully open the previously expanded row HERE.
  }

Any help would be appreciated!

Upvotes: 1

Views: 3694

Answers (1)

Quentin
Quentin

Reputation: 1933

Here is an example allowing you to extend a default table row. I hope this will help you. You will only need to retrieve the index from the tab previously opened in your data list.

TS:

export class TableExpandableRowsExample implements OnInit {
  dataSource = ELEMENT_DATA;
  columnsToDisplay = ['name', 'weight', 'symbol', 'position'];
  expandedElement: PeriodicElement | null;

  ngOnInit() {
    this.expandedElement = ELEMENT_DATA[2];
  }
}

HTML:

<ng-container matColumnDef="expandedDetail">
  <td mat-cell *matCellDef="let element" [attr.colspan]="columnsToDisplay.length">
    <div class="example-element-detail" [@detailExpand]="element == expandedElement ? 'expanded' : 'collapsed'">
      <div class="example-element-diagram">
        <div class="example-element-position"> {{element.position}} </div>
        <div class="example-element-symbol"> {{element.symbol}} </div>
        <div class="example-element-name"> {{element.name}} </div>
        <div class="example-element-weight"> {{element.weight}} </div>
      </div>
      <div class="example-element-description">
        {{element.description}}
        <span class="example-element-description-attribution"> -- Wikipedia </span>
      </div>
    </div>
  </td>
</ng-container>

StackBlitz HERE

DEMO:

enter image description here

Upvotes: 2

Related Questions