首页 > 解决方案 > 角度父组件属性更新不运行子组件中的方法

问题描述

我在父组件中有以下代码

ngOnInit(): void {
    this.service.method().subscribe(r => {
        this.data = r;
    });
}

该组件以下列方式使用子组件

        <childComponent [data]="data">
        </childComponent>

现在子组件有以下方法

ngOnInit(): void {
     if (!this.childProperty) return;

    // do some processing here
}

我遇到的问题是,最初在ngOnInit子组件上运行时没有数据,因为service.method()尚未在父组件上运行。一旦数据返回,子组件应该ngOnInit再次运行,但我该怎么做呢?

标签: angular

解决方案


您可以在模板中添加条件,例如

<childComponent [data]="data" *ngIf="data && data.length > 0">
</childComponent>

因此,一旦数据可用,就不仅仅是渲染组件。

或者

另一种方法是,您可以实现ngOnChanges()而不是ngOnInit(),因此只要输入属性发生更改(在 API 调用之后),它就会调用该钩子,您可以在该钩子中进行处理。


推荐阅读