Angular route guards

preview_player
Показать описание
In this video we will discuss CanDeactivate route guard in Angular. We will also discuss how to access angular template reference variable in component class.

Healthy diet is very important for both body and mind. We want to inspire you to cook and eat healthy. If you like Aarvi Kitchen recipes, please support by sharing, subscribing and liking.

Text version of the video

Slides

Angular CRUD Tutorial

Angular CRUD Tutorial Text Articles & Slides

All Dot Net and SQL Server Tutorials in English

All Dot Net and SQL Server Tutorials in Arabic

A routing guard called CanDeactivate can help us achieve this very easily. The following table has the common routing guards and their purpose.

Route Guard Use
------------------ --------------------------------------------
CanDeactivate Guard navigation away from the current route
CanActivate Guard navigation to a route
CanActivateChild Guard navigation to a child route
CanLoad Guard navigation to a feature module loaded asynchronously
Resolve Perform route data retrieval before route activation

We will discuss each of these routing guards with an example in our upcoming videos. In this video we will discuss CanDeactivate guard.

There are 3 steps to use a routing guard in Angular.
1. Build the route guard

2. Register the guard with angular dependency injection system

3. Tie the guard to a route

Building the route guard : A route guard can be implemented as a function or a service. In this video let's create a service. In our upcoming videos we will discuss creating a function.

export class CreateEmployeeCanDeactivateGuardService
implements CanDeactivate<CreateEmployeeComponent> {

canDeactivate(component: CreateEmployeeComponent): boolean {
return confirm('Are you sure you want to discard your changes?');
}

return true;
}
}

Code Explanation :
1. Since we are implementing the routing guard as a service, decorate the guard class with @Injectable() decorator.

2. Since we want to implement CanDeactivate routing guard, make the guard class implement CanDeactivate interface.

3. CanDeactivate interface supports generics. In our case, since we are creating a guard for CreateEmployeeComponent, we have specified CreateEmployeeComponent as the argument for the generic type of CanDeactivate interface.

4. CanDeactivate interface has one method called canDeactivate(). Our routing guard class needs to provide implementation for this interface method.

5. canDeactivate() method returns true or false. True to allow navigation away from the route. False to prevent navigation.

6. The first parameter that is passed to the canDeactivate() method is the CreateEmployeeComponent. We are using this parameter to check if the component is dirty. If it is dirty, we are triggering JavaScript confirm dialog to the user.

How to check if the form is dirty : Include the following line of code in CreateEmployeeComponent class
@ViewChild('employeeForm') public createEmployeeForm: NgForm;

@ViewChild() decorator provides access to the NgForm directive in the component class. employeeForm which is passed as the selector to the @ViewChild() decorator is the form template reference variable.

The public property "createEmployeeForm" is used to check if the form is dirty.

Register the guard with angular dependency injection system : Since the routing guard is implemented as a service, we need to register it in a module.

@NgModule({
declarations: […
],
imports: […
],
providers: [CreateEmployeeCanDeactivateGuardService],
bootstrap: [AppComponent]
})
export class AppModule { }

const appRoutes: Routes = [
{
path: 'list', component: ListEmployeesComponent
},
{
path: 'create',
component: CreateEmployeeComponent,
canDeactivate: [CreateEmployeeCanDeactivateGuardService]
},
{
path: '', redirectTo: '/list', pathMatch: 'full'
}
];
Рекомендации по теме
Комментарии
Автор

Thanks Venkat a lot i learned a lot of things from u.... u will be always remembered and i will always recommended your all tutorial to all programmers..

BakarGames
Автор

After Angular can you please start ReactJS Videos. There are so many ReactJS Videos but No One Explains the way you do. You are Legend

daviddonadze
Автор

Very nicely explained sir!!
Instead of register service in module provider, is it fine if I register in provider of createEmployee component itself within decorator?

khatkolekomal
Автор

I had an error on ViewChild: Expected 2 arguments, but got 1.
Fixed this error:
@ViewChild('employeeForm', {static: false}) public createEmployeeForm: NgForm;

jonathansansens
Автор

The greatest of them all. thank you a lot!!!

bmiguelmf
Автор

NgForm in component is undefined, what to import

sanjibanichoudhury
Автор

Is it possible to use custom confirmation box such as material dialog instead of window.confirm()?

itsimpl
Автор

If we hit browser back button once, the guard is called and select Cancel. Then if we click the browser back button again, the actual back happens. Seems an open Angular bug.

janarthanasp
Автор

Rather than on the route, is it possible to guard the destruction of the form?

continental_drift
Автор

the guard is showing the confirm alert by clicking submit button also?

tharund
Автор

Thankyou for this video, helped me a lot!

aasthawadhwa
Автор

Thank you for sharing this informative video! 🐻🖐🏻

pandarzzz
Автор

this works just fine, however it still shows that message after i make changes to the form update it and try to navigate to another route. How do i prevent that.

ashutoshshrestha
Автор

what are scenario where we can use custom directives in projects??

gkmishra
Автор

candeactivate guard does not work for me. code is simple and i have performed all your steps show in video instead of this it is not showing alert box with message. any suggestion?

murkmemon
Автор

Sir..is it possible to use the custom modal popup instead of using the confirm dialog box?

siva
Автор

any1 knows how to do guard that controls multiple components ? (with a condition common to all the components)
thanks !

orz
Автор

Getting an error - VM39061 core.js:1665 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'dirty' of undefined
TypeError: Cannot read property 'dirty' of undefined

I'm using Reactive Form. Please help

swethapallavig