1

I have the following routing:

path: 'task', component: TaskComponent, children: [ { path: ':category/:id', component: TaskEditComponent } ] 

on my TaskComponent, I have a list of div that are clickable and will redirect to the path above

<div *ngFor="let url of urlList; let i = index" (click)="goToLink(url)"> 

this urlList contains: /task/personal/10 where personal is the category and 10 is the id.

Now on my TaskComponent, I have the goToLink method:

goToLink(url: string) { this._router.navigate([url]); } 

Now this is working, I can see that my url is changing. But i am not hitting the constructor or the OnInit method of the component specified on my routing which is TaskEditComponent. Please note that on first load, I am able to hit the constructor, but when I click other url on my div, i am not hitting it.

export class TaskEditComponent implements OnInit, OnDestroy { constructor() { } ngOnInit() { console.log('should hit this') } } 

I am reading life cycle hooks but I need help on what I am doing wrong here.

5
  • this is most likely due to router reusing the component, try adding the following to the constructor of the TaskEditComponent: constructor(r: ActivatedRoute) { r.url.subscribe((s:UrlSegment[]) => { console.log("url", s); }); }, do you get logging when changing states? Commented May 23, 2017 at 7:51
  • yes, it is logging now. thanks for the help! Commented May 23, 2017 at 8:00
  • sure, can I post it as an answer? Commented May 23, 2017 at 9:37
  • Yes of course you can. Commented May 24, 2017 at 0:50
  • done, you can accept it now, thanks Commented May 24, 2017 at 4:59

1 Answer 1

1

If only the route parameters change, Router reuses the component instance and doesn't instantiate it, so constructor and onInit don't get called. So if you've been here:

/task/personal/10 

and now navigate to

/task/personal/11 

only the parameter changed, so the component will be reused. An easy way to verify it is to put the following in the constructor:

constructor(r: ActivatedRoute) { r.url.subscribe((s:UrlSegment[]) => { console.log("url", s); }); } 

It should log every time you switch the route.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.