【发布时间】:2020-04-19 23:21:01
【问题描述】:
请查看Stackblitz Editor 链接。我已经设置了一个角度应用程序。
Angular 应用的简要工作概述
- 两个组件,即应用组件和子组件
- 最初,子组件不显示。当我们点击按钮时,父应用组件中有一个按钮,我们启用一个变量'this.showChildComponent = true'。
- 由变量 this.showChildComponent 控制的子组件。
- 我使用 'firstParam' 和 'secondParam' 作为变量并将这些变量值发送到子组件。
现在,请看问题
当我们单击上面解释的按钮时,将调用已安装的子组件和 ngOnInit 方法,您也可以在控制台屏幕上查看消息“ngOnInit called: child component”但是如果我再次点击按钮,然后子组件不再重新渲染,因此子组件的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 方法。
【问题讨论】:
-
当用户再次点击按钮时,你想在子组件中实现什么?
-
@YogendraR 每当用户点击按钮时,应该调用子组件的 ngOnInit 方法。
-
这就是我要问的,你想在每次点击按钮时在 ngOnInit 中做什么。这里的用例是什么?如我所见,您也不想破坏孩子。
-
@Shubham 在更改检测有机会读取到更改之前,您已将其设置为 false 和 true。这意味着子组件不会被删除然后重新添加。这就是为什么它使用超时来工作的原因,因为超时将在更改检测后执行。如果您真的希望行为在 ngOnInit 中运行,那么您需要使用 settimeout 来等待组件被销毁。
-
@jgerstle 感谢您的投入和时间。但是是否有替代方法来销毁子组件?
标签: javascript angular