If the mat table you added to your Angular application contains a huge amount of data, there are more chances that it will either overlap or push its neighboring elements and make the page irresponsive.
To avoid this problem, we have to make its header sticky and the data inside of it vertically scrollable.
So, if you want to make the mat table vertically scrollable, you have to follow the below steps:
- Make the table header sticky by applying
sticky: true;
inside*matHeaderRowDef
. - Put the mat table inside of a container div and set its height to a fixed value such as 400px.
- Apply
overflow: auto;
on this container div element.
Let’s say we have a mat table with 3 columns Id, name, and email. As we have to make its header sticky, therefore, we have to apply a property sticky: true;
inside the mat header row definition.
Also, you have to put this whole mat table inside of a div container. See the following HTML code:
<div class="table-container"> <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <!-- Id Column --> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef> Id </th> <td mat-cell *matCellDef="let element"> {{element.id}} </td> </ng-container> <!-- Name Column --> <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDef> Name </th> <td mat-cell *matCellDef="let element"> {{element.name}} </td> </ng-container> <!-- Email Column --> <ng-container matColumnDef="email"> <th mat-header-cell *matHeaderCellDef> Email </th> <td mat-cell *matCellDef="let element"> {{element.email}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns;sticky: true;"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> </div>
Now, to make this table vertically scrollable, we have to give a fixed height to its container(div in our case) and set the overflow
property to auto
.
The property overflow: auto;
will add a vertical scrollbar if the table’s content exceeds its container height, otherwise, no scrollbars will be added.
So, add the below code in your component’s CSS file:
.table-container{ height: 400px; overflow: auto; /* adds scrollbars if needed */ } table{ width: 100%; }
In our case, we have set the table’s container height to 400px. This means if the table’s height exceeds 400px, a vertical scrollbar will be added. This will make the table’s header sticky and its content scrollable.
Here is what we get after applying the above styles:
Conclusion
In this article, we have learned how we can make a mat table vertically scrollable if it has a large amount of data. We have achieved it in three simple steps. First, make the table header sticky, second, put the mat table inside of a container and give a fixed height to it and in the last step apply overflow: auto;
on the container.