Max Koretskyi
Max Koretskyi

Reputation: 105439

Why is components constructor called multiple times while it has to be reused by router

I'm reading this article where the author states the following:

To avoid unnecessary DOM modifications, the router will reuse the components when the parameters of the corresponding routes change.

And he continues with the example where MessageCmp is reused. As I understand, it's not destroyed and re-created, hence the observables are used to track chanages:

class MessageCmp {
  message: Observable<Message>;
  constructor(r: ActivatedRoute) {
    this.message = r.data.map(d => d.message);
  }
}

I have the following route configuration:

path: 'tasks',
component: ExTasksComponent,
children: [
  {
    path: '',
    component: ExTaskListComponent,
  },
  {
    path: ':id',
    component: ExTaskViewComponent,

So I was expecting that ExTaskViewComponent will be reused when navigating from /tasks/3 to /tasks/4. However, the constructor of the component is executed each time the navigation occurs? Am I missing something?

I'm navigating using routerLink directives.

Upvotes: 3

Views: 2456

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105439

The problem was that I had the following navigation steps:

/tasks/3
/tasks
/tasks/2

And hence the component got destroyed when navigating to /tasks. I was under impression that the router state is preserved for some time and not destroyed immediately when navigating out of the current route.

Upvotes: 2

Related Questions