koral koral - 11 months ago 78
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


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

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

ngOnInit(): void {
.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
DashboardComponent ngOnInit
. Click on
and back on
- again 2 logs: constructing and calling

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
to have those console logs. Result - the same.

I've added
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 Source

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.