我试图创建新组件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人被打了两次电话?

推荐答案

为什么叫两次

现在,如果在检测组件的内容/视图子级的更改时发生错误,ngOnInit将被调用两次(见DynamicChangeDetector).

这些信息来自这github issue


因此,您的错误似乎可能源于代码中与此组件相关的其他地方.

Angular相关问答推荐

Angular 17自定义指令渲染不起作用'

笔刷Angular 为17

我应该对我想要在我的Angular 17+组件中显示的任何变量使用信号吗?

在指令中获取宿主组件的templateRef

Angular 16:信号更新未能更新视图

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

使用 Observable 进行渐进式填充

MatTooltip 显示在 html 原生对话框下方

Angular:组件的内容投影访问数据

Angular 13 - 何时创建嵌入式视图?

无法推送 Angular 项目 - Github

尽管模型中的变量发生了变化,但Angular 视图没有更新

异步管道模板中的局部变量(Angular 2+)

使用 NPM 安装 Font Awesome 5

Angular 2:Validators.pattern() 不工作

在Angular 4中以'yyyy-MM-dd'格式获取当前日期

如何在 Angular2 中的所有请求的请求标头中发送Cookie?

Angular 2 setinterval() 继续在其他组件上运行

找不到@angular/common/http模块

在渲染视图/模板之前等待 Angular 2 加载/解析模型