angular - 如何使用 *ngFor 仅显示最后 5 条消息
问题描述
我有一种情况,我*ngFor
在一些传入消息上的循环是这样的。
<ul id="messages">
<li *ngFor="let message of messages;let i = index">
<span id="actualMessage" [innerHTML]="isSystemMessage(message,i)"></span>
</li>
</ul>
现在,我isSystemMessage
像这样处理它
public isSystemMessage(message: string,i:number) {
return "<strong>" + i+': '+message + "</strong>"
}
现在,它可以很好地显示消息,但是如果我只想查看最后 5 条消息并删除它上面的所有条目怎么办?
我想添加一些这样的代码。
public isSystemMessage(message: string,i:number) {
if (i+1==5) {
// TODO: Delete the all the other entries from the webpage and only show last 5 at a time?
}
return "<strong>" + i+': '+message + "</strong>" // otherwise, return the message
}
有什么方法可以删除条目并从 UI 中删除它们?
解决方案
您可以使用slice
<div *ngFor="let message of messages | slice: (messages.length > 5 ? messages.length - 5 : 0); index as i">{{message}}</div>
这是一个现场示例:https ://stackblitz.com/edit/limit-ngfor-in-angular?file=src%2Fapp%2Fapp.component.html
推荐阅读
- apache-spark - 在单个 EMR 集群中调用多个 Spark 作业
- algorithm - 特定情况下两个嵌套循环的时间复杂度
- mysql - 如何将以下 3 个 select 语句包含在单个 mySQL 视图中
- node.js - 为什么 bodyParser 返回未定义?
- c++ - 如何在序列中找到数字的位置?
- java - 在 Java 11/12 下无法加载 Bouncy Castle 安全提供程序
- go - 从自定义客户端终止 Dialogflow 应用程序
- c++ - 关于获取行和字符串查找功能的问题
- c - 在制作 2 组数组的总和时遇到问题
- function - 如何直接添加函数返回的多个值