Why is ngOnInit called twice?

AngularNgoninit

Angular Problem Overview


I trying to create new component, ResultComponent, but its ngOnInit() method is getting called twice and I don't know why this is happening. In the code, ResultComponent inherits @Input from the parent component mcq-component.

Here is the code:

Parent Component (MCQComponent)

import { Component, OnInit } from '@angular/core';

@Component({
	selector: 'mcq-component',
	template: `
		<div *ngIf = 'isQuestionView'>
			.....
		</div>
		<result-comp *ngIf = '!isQuestionView' [answers] = 'ansArray'><result-comp>
	`,
	styles: [
		`
			....
		`
	],
	providers: [AppService],
	directives: [SelectableDirective, ResultComponent]
})
export class MCQComponent implements OnInit{
      private ansArray:Array<any> = [];
	....
	constructor(private appService: AppService){}
	....
}

Child Component (result-comp)

import { Component, OnInit, Input } from '@angular/core';

@Component({
	selector:'result-comp',
	template: `
		<h2>Result page:</h2>

	`
})
export class ResultComponent implements OnInit{
	@Input('answers') ans:Array<any>;

	ngOnInit(){
		console.log('Ans array: '+this.ans);
	}
}

When run, console.log is showing up two times, the first time it shows the correct array but the second time it gives undefined. I've not been able to figure it out: why is ngOnInit in ResultComponent getting called twice?

Angular Solutions


Solution 1 - Angular

Why it is called twice

> Right now, if an error happens during detecting changes of content/view children of a component, ngOnInit will be called twice (seen in DynamicChangeDetector). This can lead to follow up errors that hide the original error.

This information comes from this github issue


So it seems that your mistake might have an origin elsewhere in your code, related to this component.

Solution 2 - Angular

This was happening to me because of a faulty component html. I had forget to close the selector tag in the host component. So I had this <search><search>, instead of <search></search> - take note of the syntax error.

So related to @dylan answer, check your component html structure and that of its parent.

Solution 3 - Angular

if you used platformBrowserDynamic().bootstrapModule(AppModule); in app.module.ts comment it and try. I had the same problem. I think this helps

Solution 4 - Angular

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 bootstap property along with ‘parent component’. Passing the child components in bootstap 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
    })

Solution 5 - Angular

This may happen because you set the AppComponent as your base route

RouterModule.forRoot([
    { path: '', component: AppComponent }  // remove it
])

Note: AppComponent is called by default in angular so need not to call it as you can see below:

@NgModule({
  declarations: [
    AppComponent,
  ],
  bootstrap: [AppComponent] // bootstraping here by default
})
export class AppModule { }

Solution 6 - Angular

The ngOnInit() hooks only once after all directives are instantiated. If you have subscription insidengOnInit() and it's not unsubscribed then it will run again if the subscribed data changes.

In the following Stackblitz example I have subscription inside ngOnInit() and console the result. It console twice because it loads once and data changes and it loads again.

Stackblitz

Solution 7 - Angular

Putting this here in case someone wind up here. NgOnInit can also be called twice if your browser's default button type is "submit", say if you have the below, NgOnInit of NextComponent will be called twice in Chrome:

<button class="btn btn-primary" (click)="navigateToNextComponent()">

To fix it, set type:

<button class="btn btn-primary" type="button" (click)="navigateToNextComponent()">

Solution 8 - Angular

This happens whenever there are any template errors.

In my case I was using a wrong template reference and correcting that fixed my issue..

Solution 9 - Angular

This happened to me because I had unnamed <router-outlet>s inside of an *ngFor. It loaded for each iteration in the loop.

The solution, in that case, would be to have a unique name for each outlet or make sure that there is only one in the DOM at a time (perhaps w/ an *ngIf).

Solution 10 - Angular

In my case, build generated duplicates of each file main-es5.js and main-es2015.js, deleting all *-es5.js duplicates and it worked.

If that is your case too, don't delete the duplicates just add those attributes

<script src="elements-es5.js" nomodule defer>
<script src="elements-es2015.js" type="module">

Solution 11 - Angular

This can happen if you have multiple router outlets like this:

<ng-container *ngIf="condition">
  <div class="something">
    <router-outlet></router-outlet>
  </div>
</ng-container>
<ng-container *ngIf="!condition">
  <div class="something-else">
    <router-outlet></router-outlet>
  </div>
</ng-container>

Note that if you do this it can also end up calling the constructor twice. The fact that the constructor is called twice is evidence that the component is being created twice, which is exactly what happens when a component is inside an *ngIf whose condition switches from true to false to true

A useful approach to debugging this is to create a class variable called rnd like this:

rnd = Math.random()

and console.log it inside the constructor and ngOnInit. If the value changes then you know on the second call that there it is a new instance of the component and its not the same instance being called twice. Whilst this won't fix your issue, it may be indicative of the problem.

Solution 12 - Angular

In my case, this is happened when Component implements both OnChanges and OnInit. Try to remove one of these classes. You can also use ngAfterViewInit method, it is triggered after the view initialized, so that it is guaranteed to called once.

Solution 13 - Angular

I had a similar issue myself, I was calling for a component and then referencing the same component via the router-outlet.

<layout>
  <router-outlet></router-outlet>
</layout>

And the outlet route was also pointing to Layout.

Solution 14 - Angular

For me, this happened because I registered same component twice in Route:

{
        path: 'meal-services',
        children: [
          {
            path: '',
            component: InitTwiceComponent,
            canActivate: [AppVendorOpsGuard],
            data: { roleWhitelist: [UserRoles.Manage] }
          },
          {
            path: ':itemID',
            component: InitTwiceComponent,
            canActivate: [AppVendorOpsGuard],
            data: { roleWhitelist: [UserRoles.Manage] }
          }]
      },
}

Solution 15 - Angular

When I stumbled over this issue in 2021, I had just recently migrated from an ancient ng4 to a more recent ng10. The app however was integrated in a monolithic Java backend via an index.jsp, which I did not properly migrate.
If you are in a similar position check your <script> tags. The *-es2015.js sources should have a type="module" while *-es5.js should have nomodule defer set, i.e.:

<script src=".../main-es5.js" nomodule defer></script>
<script src=".../main-es2015.js" type="module"></script>

Solution 16 - Angular

In my case I did not unsubscribe to all the subscriptions that I had inside ngOnInit. I just unsubscribed from all the subscriptions within ngOnDestroy and that resolved my issue.

Solution 17 - Angular

This happened to me in a child component. The child component is to show when a certain condition is met using *ngIf. My solution is to replace ngIf with ngClass.

in HTML:

<component [ngClass]="isLoading?'hide':'show'>"

in CSS:

.show{ display: block; }

.hide{ display: none; }

Solution 18 - Angular

In my case it was a html error that caused this in app.component.html i had something like

<icpm-la-test><icpm-la-test>

instead of

<icpm-la-test></icpm-la-test>

there was two opening tags instead of closing tag. and I had no errors on console and functionality was working fine except that i had multiple api calls happening with subscriptions due to ngOnInit getting called twice.

Solution 19 - Angular

This can indicate that you are initiating the component twice by mistake. This can be for a few reasons:

  1. You have imported AppRoutingModule into more than 1 module. Search for it across your app and make sure you only have it included in the AppModule.

  2. You have imported AppModule into another module. This would also duplicate your AppRoutingModule as per point 1.

  3. You have more than one <router-outlet> in your markup. This one can get confusing, because if you have multiple nested routes, you will actually need more than one <router-outlet>. However, you will need to check that each route that has child-routes has only 1 <router-outlet>. Sometimes it is easier to copy each nested component inside the parent just to see what the actual output is going to be. Then you can see if you ended up with an extra <router-outlet> by mistake.

  4. Your wrapper component is specified in AppRoutingModule and inside the child component. Often I will have a wrapper component that handles standard layout things like header, footer, menu etc. All my child routes will then sit inside this when set out in my AppRoutingModule. Sometimes it is possible to use this wrapper component inside another component as well, thereby duplicating it as it is already specified in the AppRoutingModule. This would lead to an extra <router-outlet>.

Solution 20 - Angular

I had XComponent placed in

bootstrap: [AppComponent, XComponent]

in app.module.ts.

After removing XComponent ngOnInit was triggered only once.

Solution 21 - Angular

Solution 22 - Angular

My solution was to use ngIf in the component to prevent undefined inputs, in you case would be:

<result-comp *ngIf="answers" [answers]="answers"></result-comp>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagar GaneshView Question on Stackoverflow
Solution 1 - AngularDylan MeeusView Answer on Stackoverflow
Solution 2 - AngularparsethisView Answer on Stackoverflow
Solution 3 - AngularScott MachlovskiView Answer on Stackoverflow
Solution 4 - AngularAmardeep KohliView Answer on Stackoverflow
Solution 5 - AngularWasiFView Answer on Stackoverflow
Solution 6 - AngularMaihan NijatView Answer on Stackoverflow
Solution 7 - Angularuser3689408View Answer on Stackoverflow
Solution 8 - AngularGingerBeerView Answer on Stackoverflow
Solution 9 - AngularKevin BealView Answer on Stackoverflow
Solution 10 - AngularNourasView Answer on Stackoverflow
Solution 11 - Angulardanday74View Answer on Stackoverflow
Solution 12 - AngularCem MutluView Answer on Stackoverflow
Solution 13 - AngularCodeMylifeView Answer on Stackoverflow
Solution 14 - AngularMCMatanView Answer on Stackoverflow
Solution 15 - AngularhvspView Answer on Stackoverflow
Solution 16 - AngularSudharsan PrabuView Answer on Stackoverflow
Solution 17 - AngularPocoMView Answer on Stackoverflow
Solution 18 - AngularLakshmiView Answer on Stackoverflow
Solution 19 - AngularDoubleAView Answer on Stackoverflow
Solution 20 - AngularcdevriesView Answer on Stackoverflow
Solution 21 - Angularuser1419261View Answer on Stackoverflow
Solution 22 - AngulardazzedView Answer on Stackoverflow