[英]angular parent component property update does not run methods in child component
I have the following code in a parent component我在父组件中有以下代码
ngOnInit(): void {
this.service.method().subscribe(r => {
this.data = r;
});
}
This component is using a child component in the following manner该组件以下列方式使用子组件
<childComponent [data]="data">
</childComponent>
Now the child component has the following method现在子组件有以下方法
ngOnInit(): void {
if (!this.childProperty) return;
// do some processing here
}
The problem I'm having is that initially when ngOnInit
is run on the child component there is no data since the service.method()
has not run on the parent component.我遇到的问题是,最初在子组件上运行
ngOnInit
时没有数据,因为service.method()
没有在父组件上运行。 Once the data is back, the child component should run ngOnInit
again, but how do I do this?数据返回后,子组件应该再次运行
ngOnInit
,但我该怎么做呢?
You can add a condition in template like您可以在模板中添加条件,例如
<childComponent [data]="data" *ngIf="data && data.length > 0">
</childComponent>
So, that once the data is available, than only it render the component.因此,一旦数据可用,就不仅仅是渲染组件。
OR或者
Another way is to do, you can implement ngOnChanges()
instead of ngOnInit()
, so whenever input property get changes (after the API call) it call that hook and you can do your processing in that hook.另一种方法是,您可以实现
ngOnChanges()
而不是ngOnInit()
,因此只要输入属性发生更改(在 API 调用之后),它就会调用该钩子,您可以在该钩子中进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.