What is the best practise for controlling the size of Angular Material dialog?

Viewed 499

I want to know whether controlling the size (height, width) of dialog via CSS is preferred over specifying the size of dialog in TS file itself? What's the best practice?

1 Answers

The best practise to control the size of an Angular Material dialog is via MatDialogConfig. You will have more control with this config than with CSS, since you don't need to override Angular Material's CSS classes. In this config (see Angular Material Dialog API docs) in your component, you can specify the needs for the size of your dialog:

height: string
maxHeight: number | string
maxWidth: number | string
minHeight: number | string
minWidth: number | string
width: string

You can pass this information as second argument inside the .open() method of your dialog.

Example (see StackBlitz):

const dialogConfig = {
     maxHeight: '300px',
     maxWidth: '300px',
}
const dialogRef = this.dialog.open(DialogContentExampleDialog, dialogConfig);

Here the dialog will have a max-width and max-height of both 300px.

If you want to display different dialogs based on the user's screen width, you can use the BreakpointObserver from Angular's CDK.

Example (see StackBlitz):

  1. Import BreakpointObserver and add it to constructor.
import { BreakpointObserver } from '@angular/cdk/layout';

constructor(private breakpointObserver: BreakpointObserver) {}
  1. Add a function that calculates the dialog dimensions
getDialogDimensions() {
    const mobileDialogConfig = {
        maxHeight: '300px',
        maxWidth: '300px'
    };

    const desktopDialogConfig = {
        maxHeight: '600px',
        maxWidth: '300px'
    };

    const isMobile = this.breakpointObserver.isMatched('(max-width: 600px)');
    return isMobile ? mobileDialogConfig : desktopDialogConfig;
}
  1. Add this function as second inside the .open() method of the dialog.
const dialogRef = this.dialog.open(DialogContentExampleDialog, this.getDialogDimensions());
  1. Outcome

Small dialog

Larger dialog

Related