javascript - 在 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 列表并将其附加到列表中,但是如何?
解决方案
您可以使用Spread 运算符来执行此操作。假设您已经定义了newComment
对象。要更新视图中的列表,只需:
this.comments = [newComment, ...this.comments];
它将newComment
在列表的第一个位置插入对象。
推荐阅读
- apache-spark - 如何使用 taskContext 获取 Spark 阶段中的总分区数或任务数?
- conflict - 在 CLIPS 中,我必须使用冲突解决策略,有人可以帮我添加策略吗?
- asp.net - 从 IServiceCollection 获取服务到属性类的正确方法
- c# - dotnet publish 将 spa 文件复制到错误的输出目录
- javascript - 自动将选择扩展到一行块
- javascript - JS 对 Firefox 和 Chrome 中的不同行为进行排序
- c# - 拒绝访问路径“/data/user/0/com.companyname.hidden_wiretapping/files”。
- mysql - JSON_ARRAY() 创建单个元素数组而不是多个
- django - 异步任务完成后是否可以使用 Django Channels 刷新页面?
- spring-boot - 如何在 Spring Boot 中更快地加载 PropertySources