Angular2 router - Navigate to the current page with different parameters
Ok, after reading all your answers specially @mxii's (thank you for this), I understand that:
- when routing to the same page with different param, only the param changes. the DOM stand still, no component rebuild, no onInit cycle.
- The OnChanges hook triggers on every data-bind changes, which mean if I pass the param to child component I can't use OnInit on with this param, I must use OnChanges hook.
Good Lesson, Thanks!
The simplest way I found, by subscribing the router and then reload the page:
this.router.navigate(['page', selectedId]).then(page => { window.location.reload(); });
you can do this by using this
this.router.navigateByUrl('page_url/' + your_id);
By doing so your params will change successfully.
But it will only change your URL. If you really want to load some methods then you have to call them manually.
The page will not refresh, cause that's how the Router
works.. without refreshing the page!
You have to subscribe to the route parameters to detect changes in them and then do whatever you want to with that information..
So inject ActivatedRoute
into your component and subscribe to the parameters like this:
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.route.params.subscribe(params => {
// PARAMS CHANGED .. TO SOMETHING REALLY COOL HERE ..
// for example extract the id..
let id = +params['id']; // (+) converts string 'id' to a number
});
}