There are two ways to close a mat dialog on button click in Angular:
Both methods are easy to implement and have their own advantages. Let’s discuss each one in detail with the help of some examples:
Close Mat Dialog on Button Click using the mat-dialog-close Attribute
In this method, you have to simply add a mat-dialog-close
attribute to the button inside your template file.
Now, whenever someone clicks on this button, it will automatically close the mat dialog popup box.
Here is the code:
<button mat-dialog-close >Close Dialog</button>
Close Mat Dialog on Button Click using dialogRef.close() Method
The previous method is quite easy as we have to only add a mat-dialog-close
attribute to the button to close the mat dialog.
But, the problem is you never know when was the button clicked. OR even if you bind the button to a function which fires on button click, you can not pass data from this dialog to the parent component when it closes.
To solve all these problems, we use the close()
method of the MatDialogRef
object. The close()
method closes the mat dialog whenever it gets fired.
You can do it in two steps.
Step 1: Bind a custom function with the click event inside your template file
<button (click)="closeDialog()">Close Dialog</button>
Step 2: Now, inject the MatDialogRef<DialogComponentName>
dependency inside the dialog’s constructor and call the close()
method inside the closeDialog()
method which we bind to the button.
Here is the code implementation:
import { MatDialogRef } from '@angular/material/dialog'; export class MyDialogComponent implements OnInit { constructor(private dialogRef: MatDialogRef<MyDialogComponent>) {} closeDialog(){ // Write your stuff here this.dialogRef.close(); // <- Close the mat dialog } }