首页 > 解决方案 > 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();
        });
    }
  }

标签: angulartypescriptparent-child

解决方案


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 }}

这将始终使用更新的数据及时加载组件。


推荐阅读