本文介绍了在@Input更改时重新初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当组件输入发生更改时,是否可以告诉angular运行init(或任何其他生命周期函数或函数),或者我必须从父组件调用该函数而不是更改输入?
Is it possible to tell angular to run the init (or any other lifecycle function or function) when the component input changes or I have to call that function from the parent component instead of changing the input?
感谢您的回答!
推荐答案
当组件的输入发生更改时,将运行 ngOnChanges
生命周期挂钩.在那里,您可以根据需要调用任何其他 lifecycle挂钩或/和任何函数
.
When component's input changes, ngOnChanges
lifecycle hook runs. There you can call any other lifecycle hook or/and any function
as you want.
ngOnChanges(...args: any[]) {
console.log('onChange fired');
this.ngOnInit();
}
ngOnInit()
{
console.log('ngOnInit fired');
}
编辑:
由于某些原因,如果您想从父级调用子级的 ngOnInit
,则可以使用如下所示的 ViewChild
.
EDIT:
for some reason, if you want to call child's ngOnInit
from parent then you can make use of ViewChild
as shown below.
export class Parent{
@ViewChild(child) vc:child;
ngAfterViewInit()
{
console.log("ngAfterInit");
console.log(this.vc.ngOnInit());
}
};
export class child{
ngOnInit()
{
console.log('ngOnInit fired');
}
};
这篇关于在@Input更改时重新初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!