Angular Material Dialog Component Scrolling Issue at Startup

tonyf picture tonyf · Aug 15, 2018 · Viewed 8k times · Source

I am using Angular Material Dialog component within my app and within this dialog, I am presenting the a user a HTML table of data, that may have a scrollbar.

My issue is though, when I click the button to open the actual dialog, I noticed that the contents are immediately scrolled to the bottom, which is a nuisance, since I need to manually scroll back to the top.

I am using the standard setup as described here:

https://material.angular.io/components/dialog/overview

My dialog call is as follows:

myDialog(a: string, b: string) {
        let dialogRef = this.dialog.open(MyDialogComponent, {
            height: '500px',
            width: '800px',
            data: { a,b }
        });
}

What can I do to avoid this scroll to the bottom issue? I have tried some CSS such as top: 0; position: fixed; but to no avail.

Answer

Shay Zalman picture Shay Zalman · Feb 9, 2021

The reason it happans to you is that, the dialog component auto-focuses on the first input / button in your HTML content. You should add 'autoFocus: false' to the Dialog options to prevent it.

myDialog(a: string, b: string) {
    let dialogRef = this.dialog.open(MyDialogComponent, {
        height: '500px',
        width: '800px',
        autoFocus: false,
        data: { a,b }
    });
}