Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Component does not reinitialize for parameterized route

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"

like image 614
Mustafa Avatar asked Oct 19 '22 04:10

Mustafa


2 Answers

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?

like image 120
Günter Zöchbauer Avatar answered Oct 21 '22 02:10

Günter Zöchbauer


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.

like image 33
Jason Avatar answered Oct 21 '22 01:10

Jason