ngFor阵列更改时不重新呈现组件

时间:2018-10-16 20:16:31

标签: angular

@Component({
  selector: 'app-comment-section',
  templateUrl: './comment-section.component.html',
  styleUrls: ['./comment-section.component.css']
})
export class CommentSectionComponent implements OnInit, OnDestroy {

  @Input()
  private commentable: Commentable;
  private commentRoom;
  private comments: Comment[] = [];
  private onNew: Subscription;
  private onDelete: Subscription;

  constructor(private service: CommentingService, private http: HttpClient) { }

  ngOnInit() {
    this.commentRoom = this.service.joinCommentsRoom(this.commentable.uuid);

    this.http.get<CommentsResponse>(this.commentable.url).subscribe(res => {
      this.comments = res.comments.rows;
    });

    this.onNew = this.commentRoom.newComment$.subscribe((comment) => {
      this.comments.push(comment);
    })

    this.onDelete = this.commentRoom.deletedComment$.subscribe((uuid) => {
      console.log('Comment deleted...')
      this.comments = this.comments.filter(comment => {
        return comment.uuid != uuid;
      });
    })

  }

  ngOnDestroy() {
    this.onNew.unsubscribe();
    this.onDelete.unsubscribe();
    this.commentRoom.reconnect.unsubscribe();
  }

}

我有一个评论部分,该部分使用评论服务来获取可观察到的,发出新评论和已删除评论的部分。 一切似乎都正常,除了在创建或删除注释时更新this.comments时视图不会重新呈现。我可以看到这些值是通过console.log()发出的。

ngFor在视图中的外观如下:

<app-comment class="comment" *ngFor="let entity of comments" [entity]="entity"></app-comment>

我做错了什么导致数组更改时视图不更新吗?

亲切的问候, Axel

2 个答案:

答案 0 :(得分:0)

尝试将ngFor与尝试迭代的组件分开。

<div *ngFor="let entity of comments">
  <app-comment class="comment"  [entity]="entity"></app-comment>
</div>

有时候,在子组件不直接可见的情况下,angular的onchanges钩子不会注册更新

答案 1 :(得分:0)

NgForOf指令将跟踪默认值,即使子值正在更改,该值仍可以相同:即使更改了某些嵌套值,[Object]仍为[Object]。 / p>

您可以创建一个自定义跟踪功能以指定用于跟踪值的内容:

<app-comment class="comment" *ngFor="let entity of comments; trackBy: trackByFn" 
 [entity]="entity">
</app-comment>

函数实现必须返回使实体唯一的东西:

trackByFn(index, entity) {
  return entity.id;
}

angular.io documentation中有一个正在运行的示例。