我试图创建新组件ResultComponent
,但它的ngOnInit()
方法被调用了两次,我不知道为什么会发生这种情况.在代码中,ResultComponent
从父组件mcq-component
继承@Input
.
以下是代码:
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);
}
}
运行时,console.log
显示两次,第一次显示正确的数组,但第二次显示undefined
.我一直搞不明白:为什么ResultComponent
人中有ngOnInit
人被打了两次电话?