angular - Angular 子组件正在更新,但直到单击任意位置才能查看
问题描述
子组件更新。但是当我单击窗口上的任何位置时它就会出现。
父组件.ts
selectedId: string
Parent.component.html
<div>
<child-component [id]="selectedId"></child-component>
</div>
子组件做它应该做的事情。但是当我第二次单击时我看到更新的视图(第一次单击是打开弹出窗口并将新的 selectedId 发送给孩子)。它显示以前的 ID,直到单击。怎样才能刷新视图?
child.component.ts
@Input()
selectedId: string;
comments: Comments[];
ngOnChanges() {
if (this.selectedId) {
this.commentService
.getCommentsById(this.selectedId)
.subscribe(comments => {
this.comments = comments;
this.comments.reverse();
});
}
}
解决方案
在ngOnChanges()
函数中,您需要将changes: SimpleChanges
参数作为输入,如下所示。
ngOnChanges(changes: SimpleChanges) {
if (changes.selectedId.currentValue) {
this.loadComments(changes.selectedId.currentValue);
}
}
loadComments(id) {
this.commentService.getCommentsById(id).subscribe(comments => {
this.comments = comments;
this.comments.reverse();
});
}
除此之外,async
在您使用的任何地方添加管道,comments
就像这样{{ comments | async }}
这将始终使用更新的数据及时加载组件。
推荐阅读
- tiptap - 提示如何在 Shift-Enter 上创建段落 (p),而不是 br?
- java - Java 8流按多个属性和总和分组
- apache-spark - Pyspark 计数空值列值特定
- sql - 在 CREATE VIEW 内的 WITH...AS 中使用多个表表达式时出现“找不到对象”错误
- android - Java 函数 .asBytes() 的 Kotlin 等价物是什么?
- json - 在 VS2019 中获取“找不到方法:'Boolean Newtonsoft.Json.Schema.SchemaExtensions.IsValid”
- javascript - 使用一个组件来渲染每个 Vuetify 扩展面板项
- c# - 剑道图表 - 显示当前列值与前一列值之间的列差异
- c# - 如何获取 XML 响应的值列表?
- windows-community-toolkit - 在 UWP DataGrid 中对数据进行分组