How to Close Angular Material Dialog by Clicking Outside of the Dialog

Abstract: Configure disableClose to false in MatDialogConfig to allow users to close an Angular Material dialog by clicking outside.

Created: 2026-08-07 by
To close an Angular Material dialog when clicking outside, set the disableClose property to false in the MatDialogConfig object passed to the open() method. By default, this behavior is enabled, allowing users to dismiss the modal by interacting with the backdrop or pressing the Escape key. This guide details how to configure dialogs correctly and handle edge cases where automatic closing might be undesirable.

Understanding Default Behavior

When you open a dialog using the MatDialog service in Angular, the component automatically listens for specific user interactions to close itself. The most common interaction is clicking on the darkened overlay, known as the backdrop, that appears behind the dialog content. Additionally, pressing the Escape key typically triggers the close event.

These behaviors are controlled by the disableClose configuration option. If you do not explicitly define this option, Angular Material defaults it to false, meaning the dialog will close automatically upon these actions. Understanding this default state is crucial because many developers encounter issues when they expect the dialog to remain open but it closes unexpectedly, or vice versa.

Explicitly Configuring disableClose

To ensure your dialog closes when clicking outside, you must verify that the disableClose flag is set to false. While this is often unnecessary since it is the default, being explicit improves code readability and intent clarity for other team members. You can achieve this by passing a configuration object to the open method of the MatDialog service.

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

constructor(private dialog: MatDialog) {}

openDialog() {
  const config: MatDialogConfig = {
    disableClose: false, // Explicitly allow closing via backdrop click
    data: { message: 'Hello World' }
  };

  const dialogRef = this.dialog.open(YourDialogComponent, config);
}

In this example, the config object explicitly sets disableClose to false. When a user clicks anywhere on the screen outside the white box of the dialog, the afterClosed() observable will emit, and the dialog instance will be destroyed. This is the standard pattern for simple informational dialogs or confirmation prompts where no complex validation is required before dismissal.

Disabling Close Behavior

Conversely, there are scenarios where you must prevent the user from dismissing the dialog by clicking outside. This is common in critical workflows, such as saving sensitive data or completing a multi-step form, where accidental dismissal could lead to data loss. To implement this, you simply set disableClose to true.

const config: MatDialogConfig = {
  disableClose: true, // Prevent closing via backdrop or Escape key
  hasBackdrop: true
};

this.dialog.open(CriticalFormComponent, config);

With disableClose: true, the backdrop click listener is removed. Users can only close the dialog programmatically by calling dialogRef.close() within the child component or by adding a specific "Cancel" button that triggers this method. It is important to note that even with this setting, the dialog remains accessible via keyboard navigation if you manage focus trapping appropriately, though the Escape key behavior is also suppressed.

Handling Programmatic Closure

When you disable automatic closing, you retain full control over the lifecycle of the dialog. Inside your dialog component, you inject the MAT_DIALOG_DATA and the MatDialogRef to interact with the parent. For instance, after validating a form, you might call:

this.dialogRef.close(resultData);

This approach ensures that the dialog only disappears when your business logic permits it. It prevents race conditions where a user might click away while a network request is still pending. If you need to listen for the close event regardless of how it was triggered (programmatic or otherwise), subscribe to the afterClosed() stream in the parent component.

Managing Backdrop Visibility

Sometimes, you may want to keep the dialog open but remove the visual cue that suggests it can be closed. The hasBackdrop property controls whether the dark overlay is rendered. Setting hasBackdrop: false removes the overlay entirely, making the dialog appear as a floating panel without a shadow or dimmed background.

const config: MatDialogConfig = {
  disableClose: false,
  hasBackdrop: false // No dark overlay
};

Even with hasBackdrop: false, clicking outside the dialog will still close it if disableClose is false. However, visually, users might not realize they can click outside to close it. Therefore, UI consistency is key. If you remove the backdrop, consider providing a clear "X" button or a "Close" link within the dialog content to indicate dismissibility. This aligns with accessibility guidelines, ensuring that all users understand how to exit the modal.

Accessibility Considerations

Angular Material handles much of the heavy lifting for accessibility, including focus trapping. When a dialog opens, focus moves to the first interactive element inside it. When it closes, focus returns to the trigger element. When you disable close via backdrop, ensure that users can still navigate out of the dialog using the Tab key and eventually reach a close mechanism. Failing to provide a way to close the dialog makes it inaccessible to keyboard-only users and violates WCAG standards.

Common Pitfalls and Debugging

If your dialog is not closing when expected, check the following areas first. Ensure that you are not inadvertently setting disableClose: true elsewhere in your application logic. Review your template to see if any custom click handlers on the backdrop or container elements are preventing the default propagation or intercepting the click event.

Another common issue arises when embedding third-party libraries or complex components inside the dialog. If a child component captures mouse events, it might interfere with the backdrop click detection. In such cases, inspecting the DOM structure during runtime can reveal overlapping elements that block the click event from reaching the dialog's close listener.

For related issues regarding authentication flows that might interrupt dialog states, you may find How to Resolve an Unauthorized Response from My Angular App helpful, as network errors can sometimes reset dialog states unexpectedly. Additionally, if you are struggling with basic setup, refer to Fixing '@angular/material' Installation Failure in Your Project to ensure your environment is correctly configured.

Frequently Asked Questions

Does disabling close affect the Escape key?

Yes, setting disableClose: true disables both backdrop clicks and the Escape key press. This provides a strict mode where the dialog can only be closed programmatically via dialogRef.close().

How do I pass data back when closing?

You can pass any value to dialogRef.close(value). In the parent component, subscribe to dialogRef.afterClosed() to receive this value as an argument in the callback function.

Can I animate the backdrop removal?

Angular Material does not support animating the backdrop independently of the dialog content. Animations are handled via CSS classes applied to the dialog container. You can customize transition speeds in your global stylesheets.

What happens if I don't specify disableClose?

If omitted, the default value is false. This means the dialog will close automatically when the user clicks the backdrop or presses Escape, which is the standard behavior for most use cases.

Is it safe to remove the backdrop entirely?

Removing the backdrop (hasBackdrop: false) is safe but reduces visual affordance. Users may not realize the dialog is dismissible, so always provide an alternative close mechanism like a button or icon.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More