This utility provides an elegant system to manage Angular Material dialogs with:
- Controlled async closing (
Promise-based) - Auto-payload resolution via
getClosePayload() - Automatic Escape and backdrop click handling
- Alternating left/right dialog positions
- Support for dialog and non-dialog contexts (e.g., routed pages)
BaseAsyncDialogComponent<T, R>– base class for components that act as async dialogsDialogHelperService– helper to open dialogs with consistent styling and behavior
Copy the following files into your Angular project:
base-async-dialog.component.tsdialog-helper.service.ts
Then inject DialogHelperService wherever you want to open dialogs.
@Component({ /* ... */ })
export class MyDialogComponent extends BaseAsyncDialogComponent<MyDialogComponent, MyCloseResult> {
constructor(
@Optional() @Inject(MAT_DIALOG_DATA) override data: any,
@Optional() dialogRef: MatDialogRef<MyDialogComponent>
) {
super(dialogRef, data);
}
override async getClosePayload(action: string): Promise<MyCloseResult | false> {
if (action === 'cancel') return false;
const result = await this.saveIfNeeded();
return {
action,
data: result
};
}
}
---
2. Open a Dialog
constructor(private dialogHelper: DialogHelperService) {}
openDialog() {
this.dialogHelper
.openDialog(MyDialogComponent, { inputData: { id: 123 } })
.afterClosed()
.subscribe(result => {
console.log('Dialog closed with:', result);
});
}
---
3. Close Dialog from Inside
Inside MyDialogComponent, call:
this.tryClose('save'); // Calls getClosePayload('save')
this.tryClose('cancel'); // Can be blocked by returning `false`
---
4. Alternating Left/Right Side
Dialogs opened via DialogHelperService will alternate side (right/left) automatically.
You can override this manually:
this.dialogHelper.openDialog(MyDialogComponent, data, {
position: { left: '0' }
});
---
Features
Automatically adds a unique dialogInstanceId and backdropClass
Dialog close is delayed until getClosePayload() resolves
ESC key and backdrop click are intercepted and routed through tryClose()
Works with or without MAT_DIALOG_DATA and MatDialogRef
Stack-safe alternating layout logic
---
Advanced Tips
Combine with Angular’s @Input() + withComponentInputBinding() to reuse components in both dialogs and routes
If you need to distinguish between dialog vs. standalone mode, check this.dialogRef
---
License
MIT — use freely in commercial or open-source projects.