Why ngOnInit is getting called every time repeatedly

青春壹個敷衍的年華 提交于 2019-12-11 02:29:03

问题


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


来源:https://stackoverflow.com/questions/48088517/why-ngoninit-is-getting-called-every-time-repeatedly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!