2

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.

2 Answers 2

3

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);
  }

Example

Sign up to request clarification or add additional context in comments.

2 Comments

Now I see that the 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!
There is scrolling in there if table height is fixed. But you prevent that with its pagination feature.
1

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.