gpt4 book ai didi

javascript - Angular ngOnInit 不适用于子组件

转载 作者:行者123 更新时间:2023-12-04 13:00:03 24 4
gpt4 key购买 nike

请查看Stackblitz Editor关联。我已经设置了一个 Angular 应用程序。

Angular 应用程序的简要工作概述

  • 两个组件,即应用组件和子组件
  • 最初,子组件不显示。当我们点击按钮时,父应用组件中有一个按钮,我们启用一个变量'this.showChildComponent = true'。
  • 由变量 this.showChildComponent 控制的子组件。
  • 我使用“firstParam”和“secondParam”作为变量并将这些变量值发送到子组件。

  • 现在,请看问题

    当我们单击上面解释的按钮时,将调用子组件挂载和 ngOnInit 方法,您也可以在控制台屏幕上查看消息' ngOnInit 调用:子组件 ' 但如果我再次点击按钮,那么 子组件不会再次重新渲染,因此不会调用子组件的 ngOnInit 方法。
    // This method is defined in the app-component (parent) and it is called when user clicks on 
    // button
    showChild() {
    if (this.showChildComponent)
    {
    this.showChildComponent = false;
    }
    this.showChildComponent = true;
    // child component ngOnInit call when
    // I use the timer
    // setTimeout(()=> {this.showChildComponent = true;}, 10);
    this.firstParam = 'first param from parent';
    this.secondParam = 'second param from parent';
    }

    // Parent component - app-component
    <button (click)="showChild()">Click here to display the child component</button>

    <div *ngIf="showChildComponent">
    <app-child-component
    [first_param]="firstParam"
    [second_param]="secondParam"
    ></app-child-component>
    </div>

    正如您在代码中看到的,如果我使用 setTimeout,那么每当我单击父组件按钮时,都会调用子组件 ngOnInit 方法。 但是我不想在这里使用计时器,解决此问题的替代解决方案是什么?每当用户单击按钮时,应调用子组件的 ngOnInit 方法。

    最佳答案

    从评论中复制以提供一些引用答案:

    You have set it to false and then true before the change detection has had a chance to read that there is a change. This means that the child component will not be removed and then re-added. This is why it works by using a timeout, because the timeout will get executed after the change detection. If you really want the behavior to run in the ngOnInit then you would need to use a settimeout to wait for the component to be destroyed.



    由于您似乎不想使用 setTimeout,即使我建议这样做,您也可以使用提供的方法之一强制更改检测 here .这是 stackblitz使用第三种方法从您的原始问题中 fork 。

    关于javascript - Angular ngOnInit 不适用于子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59543932/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com