Why is ngOnInit called twice?

Shree picture Shree · Aug 5, 2016 · Viewed 62.3k times · Source

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?

Answer

Dylan Meeus picture Dylan Meeus · Aug 5, 2016

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.