why ngOnInit called twice?

2019-01-06 19:21发布

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 ?

10条回答
ら.Afraid
2楼-- · 2019-01-06 20:08

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

查看更多
成全新的幸福
3楼-- · 2019-01-06 20:10

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

查看更多
叼着烟拽天下
4楼-- · 2019-01-06 20:13

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.

查看更多
淡お忘
5楼-- · 2019-01-06 20:18

This may happen because you set the AppComponent as your default route

RouterModule.forRoot([
    { path: '', component: AppComponent }  // remove it
])

Note: AppComponent is called by default in angular so need not to call it

查看更多
登录 后发表回答