首页 > 解决方案 > 如何使用 *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 中删除它们?

标签: angulartypescriptangular6ngforangular9

解决方案


您可以使用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


推荐阅读