4

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");
Cœur
  • 37,241
  • 25
  • 195
  • 267
Neil
  • 365
  • 5
  • 8

3 Answers3

5

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:

    ngOnDestroy() {
      console.log("ngOnDestroy InDashBoard");
    }
Vega
  • 27,856
  • 27
  • 95
  • 103
hayden
  • 2,643
  • 17
  • 21
1

Well the Problem in my case was the way I was bootstrapping the Child Components. In my @NgModule decorator’s metadata object ,I was passing child component in the bootstrap property along with parent component. Passing the child components in bootstrap property was resetting my child components properties and making OnInit() fired twice.

@NgModule({
 imports: [ BrowserModule,FormsModule ], // to use two-way data binding ‘FormsModule’
declarations: [ parentComponent,Child1,Child2], //all components
 //bootstrap: [parentComponent,Child1,Child2] // will lead to errors in binding Inputs in Child components
 bootstrap: [parentComponent] //use parent components only
 })
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0

I could be wrong but I believe you want OnInit to fire twice. You need to be able to determine the initial instantiation of the component separate from sequential instantiations. So if I want something to be executed the first time and only the first time I put it in the constructor. If the component is not Lazy loaded the constructor will only get called on the initial instantiation. But if I want to call something every time the route returns to the component it goes in the onInit.