Displaying only the most recent 5 messages using *ngFor

I'm facing a situation where my *ngFor loops through incoming messages in this structure.

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

Currently, I'm dealing with it using the isSystemMessage method like this:

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

While it works fine, I now want to limit the displayed messages to only the last 5 and delete any entries above them. But I'm unsure how to achieve this. Here's what I'm considering:

public isSystemMessage(message: string, i:number) {
        if (i+1 == 5) {
            //TODO: Remove all other entries from the webpage and display only the last 5.
        }
        return "<strong>" + i + ':  ' + message + "</strong>" // otherwise, return the message
    }

Is there a way to remove entries and update the UI accordingly?

Answer №2

This method allows you to display only the most recent five messages.

<ul id="messages">
  <li *ngFor="let message of messages;let i = index">
      <span *ngIf="(messages.length>5 && messages.length-i <= 5) || messages.length<=5" id="actualMessage" [innerHTML]="isSystemMessage(message,i)"></span>
  </li>
</ul>

Do you find this method useful?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Version 4.0 of Electron-React-Boilerplate has encountered an error: The property 'electron' is not recognized on the type 'Window & typeof globalThis'. Perhaps you meant to use 'Electron' instead?

I encountered an error while attempting to call the IPCrenderer using the built-in context bridge. The error message reads as follows: Property 'electron' does not exist on type 'Window & typeof globalThis'. Did you mean 'Elect ...

The Response Header for JWT in Angular2 Spring Boot is not appearing

I am encountering an issue with my Angular2 client, Angular-cli, Spring Boot 1.4.0, and jwt setup. When I sign in from my Angular2 client, I am unable to retrieve the jwt token. My security configuration is as follows: @Configuration @Order(SecurityPrope ...

Express and Angular 5 service worker facing compatibility issues

For the past couple of days, I've been struggling with my Angular5 service worker. However, after some investigation, I believe the issue lies in the way I am serving the application. If you're interested in the detailed journey leading up to thi ...

Angular: Display a null value retrieved from an asynchronous data source

When retrieving data from the backend (Node.js/Express.js + Oracledb), there are null values present. I need to display "Null" in the HTML table wherever these null values exist. Is there a way to achieve this? This is my code: .component.html <div cl ...

Whenever a file is chosen, I aim to generate the video HTML dynamically and display the video with play functionalities using Angular 2 and TypeScript

I am attempting to allow users to select a video file and display it so they can play it after choosing the file. Below is my HTML code: <br> <input type="file" (change)="fileChangeEvent($event)" placeholder="upload file..." class=" ...

Using callback functions with server.listen in Typescript and JavaScript

I'm puzzled why the following codes are not functioning in TypeScript. (They used to work perfectly fine in my previous JavaScript code!) http.createServer(app).listen(port, (err) => { # Do something }); However, this code works flawlessly (wi ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

Troubleshooting a TypeScript and Node.js FileSystem problem

I recently encountered a strange issue with my simple TypeScript program. /// <reference path="node-definitions/node.d.ts" /> import fs = require('fs'); fs.writeFileSync("test.txt","HelloWorld"); When I try to run it, the console outputs ...

Error: Unable to inject null value into injector chain [c -> n -> J -> J -> J]

As I delve into an older angular project that was created by a former colleague, I am faced with the task of debugging it. However, as I run the application, I encounter the following error message: NullInjectorError: R3InjectorError(n)[c -> n -> J - ...

Can you explain the meaning of the TypeScript code snippet below?

Recently, while going through the declaration file of reflect-metadata library, I came across the following code snippet. It appears that the function metadata is expected to return an object with 2 functions. Could someone kindly explain the purpose of ...

Is there a way to access VMWare localhost on a mobile device?

Currently, I am utilizing VM Ware for my development tasks and I am working on creating some responsive design code. Instead of using the web-developer tools' responsive layout emulator, I would like to view it in action on my mobile device. I am look ...

An issue arises when trying to group and sum an array of objects due to difficulty converting strings to arrays in TypeScript

Below is the provided code snippet: Definition of Interface - interface IWEXInterface { readonly Date?: string; "Exec Qty"?: string; readonly Expiry?: string; } Data Collection - let data: IWEXInterface[] = [ { Date: &qu ...

What is the best approach for setting a value to an Observable<objectType>?

I'm struggling with this piece of code where I am unable to assign the data. Can someone help me understand why it's not working? Should I consider making the data an Observable? studentObservable<Student>; ngOnInit() { this.id = this.r ...

Creating nested return types: A guide to defining function return types within a Typescript class

My large classes contain functions that return complex objects which I am looking to refactor. class BigClass { ... getReferenceInfo(word: string): { isInReferenceList:boolean, referenceLabels:string[] } { ... } } I am considering somethi ...

Guide to transforming plain text into HTML format using Angular 4

In my Angular application, I am facing the task of adding a value to an array where the value itself needs to be in HTML format. This means that when the value is displayed, it should render as HTML text. For instance, if someone hovers over the text, I ...

Deliver the commitment to the data source connection settings in TypeORM

Is it possible to retrieve the datasource connection options from AWS Parameter Store instead of storing them as environment variables in a general JavaScript question? I am having difficulty finding a solution and seeking expert advice on this matter. Th ...

Nested router-outlets in Angular are not functioning properly for routing

I'm currently facing a challenge with Angular routing in a scenario that involves nested router-outlets. The objective is to have an application-wide banner at the top, followed by a dashboard navigation component that has its own router-outlet for di ...

Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format. This is my current process: public download(data: any): void { const documentCreator = new D ...

Building SVG components in React with TypeScript and styling them using SCSS

I've been experimenting with using Webpack to import SVG files as components in React Typescript. However, I'm running into trouble when it comes to styling the SVGs with SCSS. I've tried targeting a custom attribute in my CSS selector, but ...