首页 > 解决方案 > 在 Angular 中添加记录后附加 HTML

问题描述

我有一个 Angular (v7) 项目,并且组件上有一个注释列表,如下所示。我在 *ngFor 循环中列出注释并将新注释添加到列表中。然而,我在添加新评论后重新加载列表,我认为有一种更好的方法,即通过将新添加的评论与我之前与 JavaScript 一起使用过的 HTML 相结合来附加新添加的评论。但不幸的是我没有设法定义它(可能是由于循环)。在 Angular 中可以吗?

#comment-list.html:

<div *ngFor="let comment of comments">
    <div class="p-col"> {{ comment.UserName }} </div>
    <div class="p-col-12" [innerHTML]="comment.Body"></div>
</div>

添加新评论后,我调用以下方法:

#comment-list.ts:

listComments() {
    this.loading = true;
    service.listComments(this)
        .subscribe(data => {
            this.records = data.Data;
            this.loading = false;
        });
}

我想我应该使用新添加的评论数据重新创建一个 HTML 列表并将其附加到列表中,但是如何?

标签: javascripthtmlasp.net-mvcangulartypescript

解决方案


您可以使用Spread 运算符来执行此操作。假设您已经定义了newComment对象。要更新视图中的列表,只需:

this.comments = [newComment, ...this.comments];

它将newComment在列表的第一个位置插入对象。


推荐阅读