0
votes

I currently have a router with a path set like so:

{path: "application/:id", component: ApplicationComponent}

I generate a menu of links by using an ngFor loop. it uses the index to generate a dynamic routerLink of:

routerLink="application/{{index}}"

Once clicked, it travels to the correct URL and uses my ApplicationComponent's ngOnInit method to grab the index in the url and pull a specific object out of an array in a separate class.

HOWEVER it only works for the first link you click on. If I click on link 1, it loads the page correctly with object 1's data. But when I click link 2, it travels to application/2 in the url but keeps object 1s info up. If i refresh the page and click link 2, object 2's info is shown, so I know it is pulling from the array correctly.

I suspect that once any links are clicked the ApplicationComponent uses the ngOnInit method to make the component, and then if another is clicked, this method is not called so the variables are not getting updated.

How can I solve this problem? I need the Application Component to know that ive traveled to a new sublink so it can call ngOnInit again

1

1 Answers

0
votes

ngOnInit is only called once, when the component is loaded. So if you navigate to application/1, ngOnInit is called. If you then navigate to application/2, ngOnInit is not called again because the component is already loaded. You need to use something like paramMap from ActivatedRoute to detect when a parameter changes.

ngOnInit(){
    this.activatedRoute.paramMap.subscribe(paramMap => {
        let id = paramMap.get('id'); // id gets updated whenever parameters change

        // add or call any code that needs to re-run when a parameter changes here
    });
}