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 ?
if you used
platformBrowserDynamic().bootstrapModule(AppModule);
in app.module.ts comment it and try. I had the same problem. I think this helpsWell 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.
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.
This may happen because you set the
AppComponent
as your default routeNote:
AppComponent
is called by default inangular
so need not to call it