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.
It is not possible out of the box, but you can solve it with a little custom code. Take a look at this discussion and this solution (not from me, but the basis for this answer).
In short: Use the material table and add a click-method to the rows:
Add a component for the expanded area. The
row_detail.html
contains the html which is in the expanded area.In your component where the table lives you need the method to expand the row. First, add this to your component...
... and then add the method:
When CDK was the only way to get something close to a
Material Table
, usingmd-row
's in a regular table was a viable alternative, but since@angular/material 2.0.0-beta.12
ditchedCDK
tables and now have their own Data Tables that might fit your needs. See documentation below:https://material.angular.io/components/table/overview
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 themat-row
component with amatRipple
directive. When you click on a row the row element will be assigned to theexpandedElement
variable: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:
Important is here the already mentioned
when
predicate. This calls aisExpansionDetailRow
function that is defined in the component itself and checks if the row has adetailRow
property:Since RC0 the first param is the index:
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:If you would log the
rows
variable to the console output, it will look like this:Here is how you can do it with Angular Material. This example includes pagination and one example with mat-sort-header on the 'name' column. I had to override mat paginator and do a custom sort to make sure the expandable row was still by its parent when it was sorted. This example also allows you to open multiple rows at a time and to close all rows
https://stackblitz.com/edit/angular-material2-issue-zs6rfz