我试图创建一个新的组件,ResultComponent
,但是它的 ngOnInit()
方法被调用了两次,我不知道为什么会这样。在代码中,ResultComponent
继承了父组件 mcq-component
的 @Input
。
以下是代码:
父组件(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){}
....
}
子组件(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
会被调用两次?