【发布时间】:2021-11-25 08:23:39
【问题描述】:
我试图创建新组件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 会被调用两次?
【问题讨论】:
-
代码不可运行时请不要使用截图功能。
-
对不起,我使用了 sn-p 功能,但实际上我无法使用 {} 功能插入代码。
-
{} 从来没有任何问题。出了什么问题?
-
代码无法在代码区域内正确设置。 :(,这就是问题所在。