'Why is ngOnInit called twice?
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?
Solution 1:[1]
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:[2]
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:[3]
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:[4]
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:[5]
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:[6]
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.
Solution 7:[7]
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:[8]
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:[9]
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:[10]
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:[11]
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 12:[12]
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 13:[13]
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 14:[14]
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 15:[15]
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:[16]
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:[17]
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:[18]
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:[19]
This can indicate that you are initiating the component twice by mistake. This can be for a few reasons:
You have imported
AppRoutingModule
into more than 1 module. Search for it across your app and make sure you only have it included in theAppModule
.You have imported
AppModule
into another module. This would also duplicate yourAppRoutingModule
as per point 1.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.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 theAppRoutingModule
. This would lead to an extra<router-outlet>
.
Solution 20:[20]
I had XComponent placed in
bootstrap: [AppComponent, XComponent]
in app.module.ts.
After removing XComponent ngOnInit was triggered only once.
Solution 21:[21]
This happened to me because I had the arribute href="#" in the anchor tag. do not use in the anchor tag . This will get fixed if you use the routerLink as per the angular code as shown below and try to avoid having ngInit(0 method in the appComponent.ts
<a class="nav-link" [routerLink]="['/login']"> Sign In. </a>
Solution 22:[22]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow