Why ngOnInit is getting called every time repeated

2019-07-18 16:40发布

问题:

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");

回答1:

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:

typescript
    ngOnDestroy() {
      console.log("ngOnDestroy InDashBoard");
    }


回答2:

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
 })