angular - 角度父组件属性更新不运行子组件中的方法
问题描述
我在父组件中有以下代码
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
再次运行,但我该怎么做呢?
解决方案
您可以在模板中添加条件,例如
<childComponent [data]="data" *ngIf="data && data.length > 0">
</childComponent>
因此,一旦数据可用,就不仅仅是渲染组件。
或者
另一种方法是,您可以实现ngOnChanges()
而不是ngOnInit()
,因此只要输入属性发生更改(在 API 调用之后),它就会调用该钩子,您可以在该钩子中进行处理。
推荐阅读
- curl - 在 RESTful 路由中触发 Celery 任务
- php - PHP-将数据库结果放入数组并附加一个变量
- java - 是否可以在 Gradle、Android 项目中使用 ApiFuture?
- dart - 在颤动中动态加载表单字段的最佳方法是什么?
- python - 使用 pytest 模拟 SQLAlchemy 数据库 URI
- python - 从句子列表中创建最常用词的词汇表的任何有效方法?
- java - 求 Recamán 数列的第 n 个值
- multithreading - 高速缓存一致性操作期间处理器是否停止
- c# - 如何使用包含从 XML 节点阅读器解析的 XML 数据的 C# 列表填充 DataGrid?
- python - 如何使用 SQLite 在 python 3.x 中修复“'int' object has no attribute 'execute'”错误?