How to Close a Mat Dialog From ts File in Angular?

To close a mat dialog from its component.ts file or programmatically, we have to inject the MatDialogRef<DialogComponentName> in its constructor.

The MatDialogRef has a built-in method close(), which you can call anytime whenever you want to close the mat dialog box.

import { MatDialogRef } from '@angular/material/dialog';

export class DialogComponent implements OnInit {

    constructor(private dialogRef: MatDialogRef<DialogComponent>) { }

    ngOnInit(): void {
    }

    closeDialog() {
      //Write your stuff here
      this.dialogRef.close(); // <- Closes the dialog
    }
}

You can also close the mat dialog from the parent component i.e. the component which is calling the mat dialog.

This is how you can do it:

import { MatDialog} from '@angular/material/dialog';

openDialog() {
    // Opens the dialog
    this.dialogRef = this.dialog.open(DialogComponent, { 
      height: '70%',
      width: '60%',
    });
}

closeDialog(){
    this.dialogRef.close(); // <- Closes the dialog box
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.