I trying to create new component, but its ngOnInit() method is getting called twice, I don't no why this is happening? Here I've created on component called ResultComponent which takes @Input from the parent component called 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);
}
}
Here console log showing 2 times: first time it shows correct array but second time it shows undefined, but I'm not able to figure out, why ngOnInit from ResultComponent getting called twice ?
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
).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:
To fix it, set type:
This happens whenever there are any template errors.
In my case I was using a wrong template reference and correcting that fixed my issue..
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.
Why it is called twice
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.
I had a similar issue myself, I was calling for a component and then referencing the same component via the router-outlet.
And the outlet route was also pointing to Layout.