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