在Angular中添加记录后追加HTML

时间:2019-05-01 20:38:50

标签: javascript html asp.net-mvc angular typescript

我有一个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列表并将其附加到列表中,但是如何?

1 个答案:

答案 0 :(得分:1)

您可以使用Spread operator 来做到这一点。假设您已经定义了newComment对象。要更新视图中的列表,只需:

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

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