Search code examples
angulartypescriptangular6ngforangular9

How to only show last 5 message using *ngFor


I have a situation, my *ngFor loops like this on some incoming messages.

<ul id="messages">
  <li *ngFor="let message of messages;let i = index">
      <span id="actualMessage" [innerHTML]="isSystemMessage(message,i)"></span>
  </li>
</ul>

Now, I handle it in my isSystemMessage like this

    public isSystemMessage(message: string,i:number) {
        return  "<strong>" + i+':  '+message + "</strong>" 
    }

Now, it displays the messages fine, but what if I only want to see the last 5 messages and delete all the entries above it?

What I thought of adding some code like this.

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
    }

Is there's any way to delete entries and delete them from the UI as well?.


Solution

  • You can do it using slice

    <div *ngFor="let message of messages | slice: (messages.length > 5 ? messages.length - 5 : 0); index as i">{{message}}</div>
    

    Here is a live example: https://stackblitz.com/edit/limit-ngfor-in-angular?file=src%2Fapp%2Fapp.component.html