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?