Angular version 2.1.0 and router version 3.1.0 were used.
During the creation of a dashboard component, I observed that every time I route to it, it is recreated from scratch. This same behavior was noted in the Tour of Heroes demo plunker as well.
Modifications made to the 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')
}
}
A link to the plunker is provided. Opening the developer console and running the plunker will generate 2 logs: DashboardComponent constructor
and DashboardComponent ngOnInit
. Clicking on Heroes
and then back on Dashboard
triggers the construction and initialization methods once again.
The plunker may be using outdated libraries. By cloning TOH from John Papa's GitHub repository (which uses the same versions of Angular and router), and adding console logs to the DashboardComponent
, the same behavior was observed.
An additional method ngOnDestroy
was added to the DashboardComponent
, which gets called when leaving the dashboard. It appears to be a design behavior. The question arises about the benefits of this behavior and how already created components can be reused.