Is there any way to scroll the Angular Material Table in the code behind?
I have a requirement that the table should be always at the bottom bosition when the page loads. Unfortunately paging is not an option.
Typically, scrollable elements in angular material with scroll capability use cdkScrollable directive, but it doesn't seem to be the case with mat-table
So for now you could bypass it by directly accessing the element, and scroll to a high y value
scrollBottom() {
document.querySelector('mat-table').scrollBy(0, 10000);
}
mat-table doesn't have scrollbars at all, maybe that's why it doesn't have the directive.The scrollbars were in a the div container of the mat-table. I applied the .scrollBy() method to the div and it worked perfectly, thank you so much!To elaborate on the accepted answer, you need to scroll the table once the data has been loaded. In my case I provide various data filter options for the user and the scrolling to the bottom needs to happen when any of those are changed too. This can be achieved using a ContentObserver from the CDK Observers module.
You need to wrap the table in an element:
<div id="tableWrapper">
<mat-table>
...
</mat-table>
</div>
Then, in the component class:
...
import {ContentObserver} from '@angular/cdk/observers';
...
export class MyComponent {
constructor(private readonly contentObserver: ContentObserver) {}
ngAfterViewInit(): void {
this.contentObserver.observe(document.querySelector('#tableWrapper'))
.subscribe(this.tableContentChanged);
// Load the table data here
}
tableContentChanged() {
const table = document.querySelector('mat-table');
table.scrollBy(0, table.scrollHeight);
}
}