How would you make rows expandable in angular material tables? One requirement is that I need to be using the angular material table. I would also prefer to use the material accordion to the information provided here.
I want to click on row and show different information for each column. Im looking for something like below. If you click on row 1, rows 2 and 3 appear with different data.
multiTemplateDataRows have a different variable to hold the row's index called dataIndex . Access the row's index using let k = dataIndex . <!-- Row content--> <mat-row *matRowDef="let row; columns: displayedColumns; let k = dataIndex;" matRipple (click)="this.expandRow(row, k)"> </mat-row>
MatColumnDef extends CdkColumnDefDefines a set of cells available for a table column.
As mentioned here by Andrew Seguin this is already feasible out of the box: using the when
predicate.
See this example: https://stackblitz.com/edit/angular-material-expandable-table-rows (thx to Lakston)
Inside of the mat-table
tag you have to use the mat-row
component with a matRipple
directive. When you click on a row the row element will be assigned to the expandedElement
variable:
<mat-row *matRowDef="let row; columns: displayedColumns;" matRipple class="element-row" [class.expanded]="expandedElement == row" (click)="expandedElement = row"> </mat-row>
But now we have to add our expanded row, that is hidden by default and will be shown if the user clicks on the row above:
<mat-row *matRowDef="let row; columns: ['expandedDetail']; when: isExpansionDetailRow" [@detailExpand]="row.element == expandedElement ? 'expanded' : 'collapsed'" style="overflow: hidden"> </mat-row>
Important is here the already mentioned when
predicate. This calls a isExpansionDetailRow
function that is defined in the component itself and checks if the row has a detailRow
property:
isExpansionDetailRow = (row: any) => row.hasOwnProperty('detailRow');
Since RC0 the first param is the index:
isExpansionDetailRow = (i: number, row: any) => row.hasOwnProperty('detailRow');
If you want to have an expanded view for every row, you have to add an "ExpansionDetailRow" identified by the detailRow
property for every row like this:
connect(): Observable<Element[]> { const rows = []; data.forEach(element => rows.push(element, { detailRow: true, element })); return Observable.of(rows); }
If you would log the rows
variable to the console output, it will look like this:
Mat Table expandable rows (sorting, pagination and filtering)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With