Programming

Disable click outside of angular material dialog area to close the dialog With Angular Version 40

19 September 2026 · 11 min read

Disable click outside of angular material dialog area to close the dialog With Angular Version 40

Working with Angular Material Dialogs often requires fine-grained control over user interaction. One common requirement is to disable click outside of Angular Material dialog area to close the dialog. This ensures users interact with the dialog’s intended elements and prevents accidental dismissal, enhancing the user experience. In Angular version 4.0 and later, achieving this is relatively straightforward using the disableClose configuration option. This article dives deep into how to effectively implement this feature, exploring different scenarios and offering best practices to ensure your dialogs behave as expected. Properly managing dialog closures is crucial for maintaining data integrity and guiding users through your application’s workflow. We will cover everything from basic implementation to advanced customization techniques that will help you master Angular Material dialogs.

Understanding Angular Material Dialogs

Angular Material Dialogs provide a modal window that appears on top of the application content. These dialogs are highly customizable, allowing developers to present information, collect user input, or perform any other interaction necessary for the application. The flexibility of Angular Material dialogs makes them a powerful tool for building interactive and user-friendly applications. Understanding the core concepts of dialog configuration is key to leveraging their full potential. Key configuration options include setting the dialog’s size, position, and behavior, such as whether it can be closed by clicking outside the dialog area.

The default behavior of an Angular Material dialog is to close when the user clicks outside the dialog area. While this can be convenient in some cases, it’s often desirable to prevent this behavior to ensure the user completes the intended action within the dialog. For instance, you might want to prevent the user from accidentally closing a confirmation dialog before they’ve had a chance to confirm or cancel. This is where the disableClose option comes into play. By setting this option to true, you can prevent the dialog from closing when the user clicks outside its boundaries, forcing them to interact with the dialog’s buttons or other interactive elements. According to the Angular Material documentation [Angular Material Dialog API], the disableClose option directly controls this behavior, making it a simple yet powerful tool for managing dialog interactions.

Consider a scenario where you are building an e-commerce application and need to display a detailed product information dialog. You want to ensure that users carefully review the information before closing the dialog. By setting disableClose: true, you can prevent users from accidentally closing the dialog and missing important details, ultimately leading to a better user experience and potentially increasing sales. This also helps in preventing accidental data loss if the dialog is used to collect user input.

Implementing disableClose in Angular Material Dialog

The disableClose option is part of the MatDialogConfig object, which you pass when opening a dialog using the MatDialog.open() method. Setting disableClose to true will prevent the dialog from closing when the user clicks outside of it or presses the Escape key (unless explicitly handled within the dialog). Here’s how you can implement it:

First, you’ll need to inject the MatDialog service into your component’s constructor. This service provides the open() method, which is used to open the dialog. Next, you’ll create a configuration object for the dialog, setting the disableClose property to true. Finally, you’ll pass this configuration object to the open() method when opening the dialog. This ensures that the dialog remains open until the user explicitly closes it using a button or other interactive element within the dialog.

Here’s a code example demonstrating the implementation:

import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; constructor(private dialog: MatDialog) {} openDialog() { const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.width = '600px'; this.dialog.open(MyDialogComponent, dialogConfig); } 

In this example, MyDialogComponent is the component that represents the content of your dialog. The dialogConfig object is used to configure the dialog’s behavior and appearance. Setting autoFocus to true ensures that the first focusable element within the dialog receives focus when the dialog opens, improving accessibility. The width property sets the width of the dialog to 600 pixels, ensuring that it’s appropriately sized for the content it displays. This setup effectively disables closing the dialog by clicking outside and provides a structured dialog experience.

Advanced Customization Techniques

While the disableClose option provides a basic way to prevent accidental dialog closures, you might need more advanced customization techniques for specific scenarios. For example, you might want to conditionally disable the close behavior based on certain conditions, or you might want to provide a custom close button that triggers a specific action before closing the dialog. Angular Material provides several ways to achieve this level of customization.

One approach is to use the beforeClose and afterClosed events provided by the MatDialogRef object. The MatDialogRef object is returned by the MatDialog.open() method and provides methods for interacting with the dialog. The beforeClose event allows you to intercept the close event and perform custom actions before the dialog is closed. The afterClosed event allows you to perform actions after the dialog has been closed. These events can be used to implement custom validation logic, save data, or perform other tasks before or after the dialog is closed.

Here’s an example of using the beforeClose event to conditionally prevent the dialog from closing:

import { MatDialog, MatDialogConfig, MatDialogRef } from '@angular/material/dialog'; constructor(private dialog: MatDialog) {} openDialog() { const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.autoFocus = true; dialogConfig.width = '600px'; const dialogRef: MatDialogRef<MyDialogComponent> = this.dialog.open(MyDialogComponent, dialogConfig); dialogRef.beforeClose().subscribe(() => { if (this.dataNeedsSaving()) { if (!confirm('Are you sure you want to close without saving?')) { return false; // Prevent closing } } return true; // Allow closing }); } dataNeedsSaving(): boolean { // Logic to determine if data needs saving return true; } 

In this example, the beforeClose event is used to check if there is unsaved data in the dialog. If there is, a confirmation dialog is displayed to the user. If the user confirms that they want to close without saving, the dialog is allowed to close. Otherwise, the close event is prevented, and the dialog remains open. This provides a more user-friendly experience by preventing accidental data loss. You can learn more about dialog events from resources such as the official Angular Material documentation and community blog posts like this one on Medium [Angular Material Dialogs: Advanced Guide].

Infographic here
Best Practices and Common Pitfalls ----------------------------------

When working with Angular Material dialogs and the disableClose option, there are several best practices to keep in mind to ensure a smooth and user-friendly experience. Avoiding common pitfalls can save you time and effort in the long run.

First, always provide a clear and intuitive way for the user to close the dialog. Even if you disable closing by clicking outside the dialog area, the user should still be able to close the dialog using a button or other interactive element. This ensures that the user is not trapped in the dialog and can easily navigate back to the main application. Second, consider the context in which the dialog is being used. In some cases, disabling the close behavior might be appropriate, while in other cases, it might be more user-friendly to allow the user to close the dialog by clicking outside the area.

Here are some key points to consider:

  • Accessibility: Ensure that your dialogs are accessible to users with disabilities. Use appropriate ARIA attributes and ensure that the dialog is keyboard-navigable.
  • Responsiveness: Test your dialogs on different screen sizes to ensure that they are responsive and display correctly on all devices.

Common pitfalls include:

  • Forgetting to provide a way for the user to close the dialog, leading to a frustrating user experience.
  • Overusing the disableClose option, which can make the application feel less intuitive and user-friendly.

Consider this scenario: you are developing a complex form within a dialog. To ensure data integrity, you decide to disable closing by clicking outside. However, you forget to add a prominent “Cancel” button. Users might get stuck, unable to exit the dialog without completing the form. This highlights the importance of balancing data control with user experience. Make sure there are clear pathways to close the dialog, even when disableClose is enabled. You can also refer to online forums like Stack Overflow for more tips and solutions [Stack Overflow].

Step-by-Step Guide to Disabling Click Outside

Here’s a detailed, step-by-step guide on how to disable the click outside functionality for closing Angular Material dialogs in Angular 4.0+:

  1. Import necessary modules: Import MatDialog and MatDialogConfig from @angular/material/dialog.
  2. Inject MatDialog: Inject the MatDialog service into your component’s constructor.
  3. Create Dialog Configuration: Create a MatDialogConfig object.
  4. Set disableClose Property: Set the disableClose property of the configuration object to true.
  5. Open the Dialog: Use the MatDialog.open() method to open the dialog, passing the configuration object as an argument.
  6. Test the implementation: Run your application and verify that the dialog does not close when you click outside of it.

Here’s a snippet of the code that would go into your component.ts file:

import { Component } from '@angular/core'; import { MatDialog, MatDialogConfig } from '@angular/material/dialog'; @Component({ selector: 'app-my-component', templateUrl: './my-component.html', styleUrls: ['./my-component.css'] }) export class MyComponent { constructor(private dialog: MatDialog) {} openDialog() { const dialogConfig = new MatDialogConfig(); dialogConfig.disableClose = true; dialogConfig.autoFocus = true; this.dialog.open(MyDialogComponent, dialogConfig); } } 

The above snippet assumes that you have a button in your component’s template that calls the openDialog() method when clicked. The MyDialogComponent is the component you want to display in the dialog. Ensure that you have imported and declared MyDialogComponent in your module.

FAQ: Disabling Click Outside Angular Material Dialog

**Q: How do I prevent the Escape key from closing the dialog as well?**
A: Setting disableClose: true also prevents the Escape key from closing the dialog, unless you explicitly handle the key press within the dialog component.
**Q: Can I dynamically change the disableClose property?**
A: Yes, you can dynamically change the disableClose property based on certain conditions in your application. You would need to re-open the dialog with the updated configuration.
**Q: What Angular Material versions does this apply to?**
A: This method applies to Angular Material versions 4.0 and later, as the disableClose option is available in these versions.
**Q: Why isn't disableClose: true working for me?**
A: Double-check that you are passing the MatDialogConfig object correctly to the MatDialog.open() method. Ensure there are no conflicting event handlers that might be closing the dialog.
By implementing these strategies, you can effectively control how users interact with your Angular Material dialogs and [enhance the overall user experience](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c). Remember to consider the specific needs of your application and choose the approach that best balances data control with user-friendliness. Fine-tuning these settings can significantly improve the intuitiveness and robustness of your application.

Question & Answer :

I am currently working on password reset page of an Angular 4 project. We are using Angular Material to create the dialog, however, when the client clicks out of the dialog, it will close automatically. Is there a way to avoid the dialog close until our code side call “close” function? Or how should I create an unclosable modal?

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent { constructor(private dialog: MatDialog){} openDialog() { this.dialog.open(DialogComponent, { disableClose: true }); } } 
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent { constructor(private dialogRef: MatDialogRef<DialogComponent>){ dialogRef.disableClose = true; } } 
    

Here’s what you’re looking for:

disableClose property in material.angular.io

And here’s a Stackblitz demo


Other use cases

Here’s some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core'; import { MatDialogRef } from '@angular/material'; @Component({ selector: 'app-third-dialog', templateUrl: './third-dialog.component.html' }) export class ThirdDialogComponent { constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) { } @HostListener('window:keyup.esc') onKeyUp() { this.dialogRef.close(); } } 

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I’ve adapted Marc’s answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here’s the code:

openDialog() { let dialogRef = this.dialog.open(DialogComponent, { disableClose: true }); /* Subscribe to events emitted when the backdrop is clicked */ dialogRef.backdropClick().subscribe(() => { // Close the dialog dialogRef.close(); }) // ... } 

Alternatively, this can be done in the dialog component:

export class DialogComponent { constructor(private dialogRef: MatDialogRef<DialogComponent>) { dialogRef.disableClose = true; /* Subscribe to events emitted when the backdrop is clicked */ dialogRef.backdropClick().subscribe(() => { // Close the dialog dialogRef.close(); }) } }