Тёмный

Angular route guards 

kudvenkat
Подписаться 829 тыс.
Просмотров 83 тыс.
50% 1

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.
/ @aarvikitchen5572
Text version of the video
csharp-video-tutorials.blogspo...
Slides
csharp-video-tutorials.blogspo...
Angular CRUD Tutorial
• Angular CRUD tutorial
Angular CRUD Tutorial Text Articles & Slides
csharp-video-tutorials.blogspo...
All Dot Net and SQL Server Tutorials in English
ru-vid.com...
All Dot Net and SQL Server Tutorials in Arabic
/ kudvenkatarabic
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.
Create a new file, in the employees folder. Name it create-employee-can-deactivate-gaurd.service.ts. Copy and paste the following code.
export class CreateEmployeeCanDeactivateGuardService
implements CanDeactivate<CreateEmployeeComponent> {
canDeactivate(component: CreateEmployeeComponent): boolean {
if (component.createEmployeeForm.dirty) {
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 { }
Tie the guard to a route : Using the route guard, we want to prevent navigating away from the "create" route, so tie the route guard with the "create" route in app.module.ts file as shown below.
const appRoutes: Routes = [
{
path: 'list', component: ListEmployeesComponent
},
{
path: 'create',
component: CreateEmployeeComponent,
canDeactivate: [CreateEmployeeCanDeactivateGuardService]
},
{
path: '', redirectTo: '/list', pathMatch: 'full'
}
];

Наука

Опубликовано:

 

3 апр 2018

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 42   
@BakarGames
@BakarGames 3 года назад
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..
@bmiguelmf
@bmiguelmf 5 лет назад
The greatest of them all. thank you a lot!!!
@daviddonadze221
@daviddonadze221 6 лет назад
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
@hassansall7181
@hassansall7181 6 лет назад
Indeed
@anuragranjan6739
@anuragranjan6739 5 лет назад
Hello @David , I think you are a Angular Developer so you are on this video Series , as you have asked to upload React tutorial nearly 5 month back so I just wanted to ask did you completed React after Angular because I am a Angular Developer and I am planning to learn React , But I don't know if I will be comfortable with React after learning Angular , and how much time it took to adopt react , as A Angular developer .. was it confusing ..?
@pandarzzz
@pandarzzz 5 лет назад
Thank you for sharing this informative video! 🐻🖐🏻
@jonathansansens
@jonathansansens 5 лет назад
I had an error on ViewChild: Expected 2 arguments, but got 1. Fixed this error: @ViewChild('employeeForm', {static: false}) public createEmployeeForm: NgForm;
@salmanchowdarym1110
@salmanchowdarym1110 5 лет назад
Simply amazing
@aasthawadhwa2575
@aasthawadhwa2575 3 года назад
Thankyou for this video, helped me a lot!
@srinathreddy4910
@srinathreddy4910 2 года назад
Superb explanation thanks venkat
@ihsanullah4058
@ihsanullah4058 6 лет назад
Great sir...its too helfull
@lathakumari626
@lathakumari626 Год назад
Great explanation
@belmiris1371
@belmiris1371 6 лет назад
Thank you!
@jacksm8709
@jacksm8709 4 года назад
best guard tutorial.....
@continental_drift
@continental_drift 6 лет назад
Rather than on the route, is it possible to guard the destruction of the form?
@khatkolekomal
@khatkolekomal 4 года назад
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?
@orz5516
@orz5516 5 лет назад
any1 knows how to do guard that controls multiple components ? (with a condition common to all the components) thanks !
@csdias2004
@csdias2004 5 лет назад
Thank you
@sanjibanichoudhury7517
@sanjibanichoudhury7517 5 лет назад
NgForm in component is undefined, what to import
@hassansall7181
@hassansall7181 6 лет назад
Plz can you make a series on SignalR
@ashutoshshrestha8745
@ashutoshshrestha8745 5 лет назад
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.
@gkmishra2009
@gkmishra2009 4 года назад
what are scenario where we can use custom directives in projects??
@itsimpl6257
@itsimpl6257 5 лет назад
Is it possible to use custom confirmation box such as material dialog instead of window.confirm()?
@AlokKumar-fh9gy
@AlokKumar-fh9gy 7 месяцев назад
Hello Could you please tell if this id possible
@nigochen6665
@nigochen6665 2 года назад
Thanks
@siva6388
@siva6388 6 лет назад
Sir..is it possible to use the custom modal popup instead of using the confirm dialog box?
@anuragranjan6739
@anuragranjan6739 5 лет назад
You can try ngx-bootrap modals valor-software.com/ngx-bootstrap/#/modals
@RakeshKumar-ou8ff
@RakeshKumar-ou8ff 5 лет назад
How to work on same component
@tharund3572
@tharund3572 6 лет назад
the guard is showing the confirm alert by clicking submit button also?
@Csharp-video-tutorialsBlogspot
Good observation Tharun. Sorry, I missed to test saving the data. To fix this all we have to do is reset the form. I will record and upload a video soon that explains how to do this. Thank you very much for taking the time to let us know about this.
@kumarswamy2900
@kumarswamy2900 5 лет назад
R u uploaded this video for Q)the guard is showing the confirm alert by clicking submit button also?
@souvikpodder7187
@souvikpodder7187 5 лет назад
@@kumarswamy2900 do {yourFormName}.reset(); on Submission on your form it will work
@mohamed.elzallat
@mohamed.elzallat 3 года назад
@@souvikpodder7187 thanks man it worked
@janarthanasp
@janarthanasp 5 лет назад
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.
@ruturajharer2284
@ruturajharer2284 5 лет назад
yes , i also checked!
@ruturajharer2284
@ruturajharer2284 5 лет назад
is there any solution for that?
@murkmemon6355
@murkmemon6355 4 года назад
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?
@swethapallavig5726
@swethapallavig5726 6 лет назад
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
@kaischaabane6978
@kaischaabane6978 5 лет назад
check if you are added at the right place { path: 'create', component: CreateEmployeeComponent, canDeactivate: [CreateEmployeeCanDeactivateGuardService] },
@shri11.11
@shri11.11 2 года назад
No need of using @viewchild, directly u can write if(component.formname.dirty)
Далее
Angular route params
10:57
Просмотров 45 тыс.
CanDeactivate Route Guard - Angular (Tutorial #26)
14:32
Angular resolve guard
10:02
Просмотров 43 тыс.
CanActivate Route Guard - Angular (Tutorial #24)
11:58
Router Guards | Guard Introduction | Angular 16
10:48
Angular pure pipe
11:03
Просмотров 34 тыс.
Angular read route parameters
10:22
Просмотров 33 тыс.
Angular Router - The Basics and Beyond
11:47
Просмотров 127 тыс.