I have a javascript function inside a file i route into an ng-view in an Angular project. Is there a way to execute said function after the routing has finished? similar to JavaScript's window.onload?
-
Which version of angular are you using?Surjeet Bhadauriya– Surjeet Bhadauriya2019-12-12 06:37:54 +00:00Commented Dec 12, 2019 at 6:37
-
In the route, a component will get loaded so why not call the function in its lifecycle hook.Ramesh Reddy– Ramesh Reddy2019-12-12 06:37:56 +00:00Commented Dec 12, 2019 at 6:37
Add a comment
|
2 Answers
Yes you can use a router event, In your constructor,
constructor(private router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
// call your function here
}
});
}
Dont forget to import
import { Router } from '@angular/router';
This event is called only when the navigation is about to end.
**The sequence of router events is as follows,**
NavigationStart,
RouteConfigLoadStart,
RouteConfigLoadEnd,
RoutesRecognized,
GuardsCheckStart,
ChildActivationStart,
ActivationStart,
GuardsCheckEnd,
ResolveStart,
ResolveEnd,
ActivationEnd
ChildActivationEnd
NavigationEnd,
NavigationCancel,
NavigationError
Scroll
Here are all the navigation events you can look at the angular docs https://angular.io/api/router/Event
2 Comments
NAD
pardon my ignorance, but could you please point me to a resource where i can see more on this syntax? its unfamiliar to me and i cant seem to find any good explanation on it.
anonymous
Please have look at this link angular.io/api/router/Event
You should use NavigationEnd method from the angular routing lifecycle like this:-
import { Router } from '@angular/router';
constructor(private router: Router) {}
ngOnInit() {
this.router.events.subscribe(event => {
if(event instanceof NavigationEnd) {
**// CALL YOUR FUNCTION HERE**
}
})
}
For more reference please visit angular navigation cycle demo
1 Comment
siddharth shah
Glad to hear that