Angular Component route change confirmation with custom confirmation dialogue (mat-dialog).

Shubham
2 min readMar 10, 2021

Confirmation on closing a component that contains a form or any elements.

Scenario:

  1. Let's consider there is a form on the screen. End-user has filled almost 50% of the form. And accidentally or by purpose when the end-user clicks on the back or clicks on different tabs from the navigation.
  2. In this case, he should get an alert of confirmation like “Do you really want to close? This will discard all of your changes?”.

Solution:

1)For such a case we user canDeactivate the functionality of the Angular Router.

2) Create a service named can-deactivate-guard.service.ts
and add code in that service like:

3) Now add that newly generated CanDeactivateGuard in providers of the respective module. If we want to use that guard globally, in that case, add CanDeactivateGuard in providers of App Module.

4) Open routing module file where we have defined route/path for that component for which we have to add this functionality.

5) Here in this case we are going to add this functionality for LevelDetails component.
Previously my route for this component was like:

{ path: ‘details’, component: LevelDetailsComponent},
Now change this to:
{ path: ‘details’, component: LevelDetailsComponent, canDeactivate: [ CanDeactivateGuard ]},

6) As we have created an interface in CanComponentDeactivate we can implement that in our LevelDetailsComponent.

7) Now we need to implement canDeactivate method as we have implemented CanComponentDeactivate interface.

8) Our code for canDeactivate method in the component will be like this:

9) In this case, I have created a custom dialogue for confirmation.

10) I have added the condition that: If the form is not pristine only in this case show this confirmation dialogue otherwise don’t show confirmation.

Thank You! :)

--

--