5

I have below test route with parameter T1:

{
    path: 'Test/:T1',
    component: TestComponent
},

When I route to 'Test/2' from 'Test/1' my TestComponent does not reinitialize. Is it an issue with angular router?

I am using "@angular/router": "3.0.0-beta.1"

Mustafa
  • 202
  • 3
  • 14

2 Answers2

2

This is currently the only supported behavior. There are plans to make this configurable https://github.com/angular/angular/issues/9811

You can subscribe to parameters change and do the initialization there

export class MyComponent {
    constructor(private route : ActivatedRoute,
      private r : Router) {}

    reloadWithNewId(id:number) {
        this.r.navigateByUrl('my/' + id + '/view');
    }

    ngOnInit() {
      this.sub = this.route.params.subscribe(params => {
         this.paramsChanged(params['id']);
       });
    }

    paramsChanged(id) {
      console.log(id);
      // do stuff with id

    }
}

See also How do I re-render a component manually?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Well actually what the thread suggests is opposite of the behavior I intend to have.. But if they can make it configurable then it may work for all scenarios. – Mustafa Aug 09 '16 at 10:12
  • Depends on how you see it ;-) Currently the default behavior is like with the old `routerCanReuse() { return true; }`, but what you want seems to be `routerCanReuse() { return false; }`. – Günter Zöchbauer Aug 09 '16 at 10:15
  • Exactly.. Because I need the constructor to run every time the route is called. – Mustafa Aug 09 '16 at 10:19
  • Just move the code out of the constructor and call it from `route.params.subscribe(...)` – Günter Zöchbauer Aug 09 '16 at 10:21
  • The subscriber does work for now.. but I think the better way would be to replace it when the Router is updated. – Mustafa Aug 10 '16 at 04:46
  • 1
    the default behavior is more efficient because you don't need to re-create the whole component every time. You have the control to reset just whatever that's needed. – Shawn Jun 04 '17 at 04:58
1

After about 2 hours of searching the web for an answer to this router issue, my Solution was to forego the router and just let my component do its thing.

window.location.href = '/my/' + new_id_param + '/view';

This could also work for you if you have no guards that would prevent it from being loaded by visiting the url with the right params.

Not the "best practice way" but it works for me.

Jason
  • 206
  • 2
  • 8