Per Angular ( https://angular.io/api/core/OnInit that says ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated. ),
So ngOnInit should be called once, but as shown in the plunker ( that is a copy from https://angular.io/tutorial/toh-pt5 ) , I only modified app/heroes/heroes.component.ts and app/dashboard/dashboard.component.ts to have console.log
and when F12 (Developer Tools) is opened, the console shows the log repeatedly when route is changed.
I looked why ngOnInit called twice? , Difference between Constructor and ngOnInit , Angular 2 App Component ngOnInit called twice when using iframe , ngOnInit called everytime i change route
but could not understand why ngOnInit is being called everytime.
console.log("ngOnInit in All Heroes");
console.log("ngOnInit InDashBoard");
When the route changes the component is destroyed, then when the route changes back the component is initialised again.
Add this to
DashboardComponent
to see for yourself:Well the Problem in my case was the way I was bootstrapping the Child Components. In my
@NgModule
decorator’s metadata object ,I was passingchild component
in the bootstrap property along withparent component
. Passing the child components in bootstrap property was resetting my child components properties and makingOnInit()
fired twice.