84

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?

David Archibald
  • 1,431
  • 14
  • 27
Sagar Ganesh
  • 2,454
  • 3
  • 20
  • 32

24 Answers24

54

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.

Dylan Meeus
  • 5,696
  • 2
  • 30
  • 49
  • 3
    thanks for your response, here actually I just controller **isQuestionView** flag, that's it. – Sagar Ganesh Aug 05 '16 at 11:17
  • @Shree, can you please explain this? I am also facing the same issue... – Ravindra Thorat Feb 18 '19 at 11:23
  • @RavindraThorat Hi there are few probabilities of this, like 1. wrong closing tag (like ) 2. adding same component twice – Sagar Ganesh Feb 18 '19 at 11:45
  • thanks for the quick response, but nothing is happening in my case. I have created a thread here https://stackoverflow.com/questions/54632686/component-constructor-is-getting-called-twice-with-angular-elements. am not sure why its not working correctly – Ravindra Thorat Feb 18 '19 at 11:48
  • In my case I had a silent error related to a bad mapping between JSON objects of mine. Fixing this error prevented this double call to ngOnInit(). Thanks :) – Louis May 07 '19 at 15:18
  • ngOninit called twice only when i reload a page. can you help me out? – rahul tiwari Apr 07 '21 at 07:52
27

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.

parsethis
  • 7,998
  • 3
  • 29
  • 31
23

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
    })
Nandan Acharya
  • 900
  • 2
  • 12
  • 24
Amardeep Kohli
  • 503
  • 3
  • 7
21

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

20

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 again as you can see below:

@NgModule({
  declarations: [
    AppComponent,
  ],
  bootstrap: [AppComponent] // bootstraping here by default
})
export class AppModule { }
WasiF
  • 26,101
  • 16
  • 120
  • 128
14

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()">
user3689408
  • 155
  • 1
  • 5
  • 2
    thanks, that was exactly the issue in my case. I guess this is only relevant if your buttons are part of a `
    `, though.
    – omoser Feb 15 '17 at 15:06
14

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

Maihan Nijat
  • 9,054
  • 11
  • 62
  • 110
5

This happens whenever there are any template errors.

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

GingerBeer
  • 888
  • 10
  • 11
4

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">
Nouras
  • 129
  • 2
  • 12
4

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.

danday74
  • 52,471
  • 49
  • 232
  • 283
3

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

Kevin Beal
  • 10,500
  • 12
  • 66
  • 92
  • 1
    nice one Cyril :) I have multiple inside *ngIf - commenting one out fixed the problem - now I just need to tweak the code a bit to fix this :D you r my hero for the day – danday74 Apr 30 '21 at 08:41
3

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] }
          }]
      },
}
MCMatan
  • 8,623
  • 6
  • 46
  • 85
2

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.

Cem Mutlu
  • 1,969
  • 1
  • 24
  • 24
2

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.

CodeMylife
  • 1,321
  • 1
  • 9
  • 12
2

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; }
PocoM
  • 131
  • 1
  • 2
2

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>
hvsp
  • 327
  • 4
  • 12
1

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.

Sudharsan Prabu
  • 105
  • 1
  • 11
1

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.

Lakshmi
  • 2,204
  • 3
  • 29
  • 49
1

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>.

DoubleA
  • 1,636
  • 14
  • 28
1

I had XComponent placed in

bootstrap: [AppComponent, XComponent]

in app.module.ts.

After removing XComponent ngOnInit was triggered only once.

cdevries
  • 71
  • 1
  • 2
1

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>
user1419261
  • 829
  • 8
  • 5
1

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>
dazzed
  • 643
  • 2
  • 9
  • 19
1

In my case the problem was that Login page was getting called twice after hit Sign Out button. The cause was bad syntax on the Sign Out button. The code causing problem was:

<a routerLink="/login">
  <i class="fa fa-sign-out" (click)="logout()"></i>
</a>

Removing click event from icon tag and putting into link tag resolved the problem.

<a routerLink="/login" (click)="logout()">
  <i class="fa fa-sign-out"></i>
</a>
1

Check your main.ts file. I think on default Angular apps have these two separate references for platformBrowserDynamic(). I commented out the second one and it worked:

const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);

//platformBrowserDynamic().bootstrapModule(AppModule) // .catch(err => console.error(err));

Tom Trost
  • 9
  • 3