koral koral - 27 days ago 13
TypeScript Question

Angular 2.1 - recreating component while routing

Angular 2.1.0, router 3.1.0.

While creating dashboard component I noticed that each time I route to it - it is created from ctratch. Then I checked Tour of Heros demo plunker - same behavior.

Modifications of

DashboardComponent


export class DashboardComponent implements OnInit {
heroes: Hero[] = [];

constructor(private heroService: HeroService) {
console.log('DashboardComponent constructor')
}

ngOnInit(): void {
this.heroService.getHeroes()
.then(heroes => this.heroes = heroes.slice(1, 5));
console.log('DashboardComponent ngOnInit')
}
}


Here is the plunker. Open developer console. Run the plunker - should see 2 logs:
DashboardComponent constructor
and
DashboardComponent ngOnInit
. Click on
Heroes
and back on
Dashboard
- again 2 logs: constructing and calling
ngOnInit
.

Plunker may use old librarioes. I've cloned TOH from John Papa git (at the time of writing he uses same versions nf Angular and router) and changed
DashboardComponent
to have those console logs. Result - the same.

I've added
ngOnDestroy
to
DashboardComponent
and it is called while leaving dashboard. So it looks like ny design behavior. What are benefits? How can I reuse already created components?

Answer

This is "as designed". The component is destroyed when navigating away from a route and re-created when navigating back to the route.

The component is only kept if only route parameters change but the route stays the same.

There were discussions about some custom caching strategy but AFAIK nothing was done yet in this direction.

Comments