Search code examples
angularangular4-router

Angular Routing:Call different function on same module(or component) from different router links


I have a module named Items and i navigate to its items.Component.ts form many router links.To track from which page we came an id can be passed along with router path.

this.router.navigate(['/items',id passed along with);

But i want to call different functions as per the page i came from before ngOnit(). Ex. I want to call function A in itemscomponent if i navigated from Menu or B if i navigated from Category

Also required navigation can be done from both module(or component) html file or component.ts(view model) How can i achieve this in angular?


Solution

  • you can use queryParams and send 1 from menu page and 2 from category, and after navigate you can execute functions related to you query params

       this.router.navigate(['/items'],id, { queryParams: { functionToexecute: 1  } });
    

    and in your itemsComponent:

     constructor(
       private route: ActivatedRoute,
       private router: Router) {}
    
      ngOnInit() {
       this.route
        .queryParams
        .subscribe(params => {
         if (params['functionToexecute'] === 1){ call functionA} else{call 
          function B}
       });
     }