Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular rc3 router - Navigating to same page with different parameters

I'm currently trying to navigate to the same page with different id values. So if i am on /test/1 and go to /test/2 the url in the browser updates but the view does not refresh. I debugged ngOnInit and it did not rerun when navigating to /test/2. However if I go from test/1 to other the routing works fine, the issue only occurs when navigating to the same route with different parameters. Has anyone else come across this? When I get some time ill upload a plunkr.

Angular 2 rc3 router 3.0.0-beta.2

RouterConfig = [
    {
        path: '',
        component: 'Layout',
        children: [
            {
                path: 'test/:id',
                component: TestComponent
            },
            {
                path: 'other',
                component: OtherComponent
            }
        ]
    }
]

Thanks, LL

like image 913
kLai Avatar asked Jul 13 '16 17:07

kLai


People also ask

Can we use 2 router-outlet in Angular?

You can have multiple router-outlet in same template by configuring your router and providing name to your router-outlet, you can achieve this as follows. Advantage of below approach is thats you can avoid dirty looking URL with it. eg: /home(aux:login) etc.

Can we have multiple routes in Angular?

Angular Router supports multiple outlets in the same application. A component has one associated primary route and can have auxiliary routes. Auxiliary routes enable developers to navigate multiple routes at the same time.


1 Answers

When you navigate to same route with different param it reuse the component. Hence ngOnInit won't be called again. You should subscribe to routeparam in ngOnInit and then do the view update in subscribed function

Inject Activated route in constructor

constructor(
  private route: ActivatedRoute,
  private router: Router,......) {}

In the ngOnInit method, we use the ActivatedRoute service to retrieve the parameters for our route

ngOnInit() {
  this.sub = this.route.params.subscribe(params => {
     let id = +params['id']; // (+) converts string 'id' to a number
     //here goes your logic like below
this.service.getHero(id).then(hero => this.hero = hero);
   });
}

For more details see and section "Getting the route parameter "

like image 133
Arpit Agarwal Avatar answered Sep 22 '22 01:09

Arpit Agarwal