Angular Overlay Invocation Patterns
Angular Overlay Invocation Patterns
There are two ways to open a modal or popup via the Angular Modal Service Pattern:
1. Direct (component-driven)
The triggering component injects the service and calls openModal or openPopup directly. When the overlay closes, the result is returned directly to the triggering component via the observable returned by MatDialogRef.afterClosed().
Use when: the overlay is a local, imperative interaction tied to a specific component.
2. NgRx-driven (action → effect → service)
The triggering component dispatches a NgRx action. An effect catches the action and calls the custom service to open the overlay. When the overlay closes, the effect dispatches another action carrying the result — it cannot return a value directly to a component.
Use when: the overlay needs to be URL-bound — navigating to a specific route should automatically trigger the overlay, decoupling the trigger from any single component. When the overlay closes, the effect navigates back to the underlying URL, keeping the router state consistent.
The service returns MatDialogRef to the caller, enabling programmatic closure. This is used when the wrapped component contains a cancel button — the component calls dialogRef.close(result) directly, which triggers afterClosed() for whoever is subscribed.
In both paths, close handling is driven by subscribing to MatDialogRef.afterClosed() — the component subscribes directly in the direct path; the effect subscribes and dispatches a result action in the NgRx path.
The key distinction: the NgRx path makes overlays first-class navigation targets rather than purely imperative UI events, at the cost of routing the close result through the action stream instead of back to a component directly.