我试图创建新的组件,但其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); } }
这里的控制台日志显示2次:第一次它显示正确的数组,但第二次它显示未定义,但我无法弄清楚,为什么ngOnInit从ResultComponent得到调用两次?
为什么叫两次
原文链接:https://www.f2er.com/angularjs/144035.htmlRight now,if an error happens during detecting changes of content/view children of a component,ngOnInit will be called twice (seen in DynamicChangeDetector).
This can lead to follow up errors that hide the original error.
这个信息来自这个github issue