Displaying updated information in Angular

I recently developed a chat application using Angular that utilizes the stomp socket from @stomp/ng2-stompjs. To display all messages, I am leveraging *ngFor.

<p *ngFor="let item of messages" style="padding: 5px; font-size: 18px">
    <span style="color:darkturquoise">{{item.author}}</span>: {{item.message}}
  </p>

However, I noticed that when the messages variable is updated (confirmed with console.log), Angular does not rerender *ngFor.

this.subscription = this.messagesObs.subscribe((message: Frame) => {
  this.messages = <ResponseMessage[]>JSON.parse(message.body).slice();
  console.log(this.messages);
});

I attempted to use

this.changeDetector.detectChanges();
, but it did not resolve the issue. While I understand this is the default behavior of the framework, I am seeking an optimal way to trigger the rendering of *ngFor after each subscription.

**Update:**

I have created a sample in Plunker. Note that the example will not function as my backend is hosted on localhost.

Answer №1

To access your data, you can utilize the rxjs map operator along with the async-pipe provided by Angular for subscription. The pipe ensures that the subscription is properly handled even when the component is destroyed.

public messages$: Observable<ResponseMessage[]> = this.messagesObs.map((message: Frame) => {
  return JSON.parse(message.body) as ResponseMessage[];
});

Incorporate the following code in your component's view:

<p *ngFor="let item of messages$ | async" style="padding: 5px; font-size: 18px">
  <span style="color:darkturquoise">{{item.author}}</span>: {{item.message}}
</p>

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

Looping through arrays within objects using NgFor in Angular 2/JavaScript

I have a custom object with data that I am iterating through using ngFor. Within this object, there is an array component that I also want to iterate through in a <li></li>. Currently, the output appears as one complete string within each < ...

Why is the ionChange/ngModelChange function being triggered from an ion-checkbox even though I did not specifically call it?

I have an issue with my code involving the ion-datetime and ion-check-box. I want it so that when a date is selected, the checkbox should automatically be set to false. Similarly, if the checkbox is clicked, the ion-datetime value should be cleared. Link ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

Prevent additional functions from running when clicking in Angular 5

I have implemented an Angular material table where each row expands when clicked. In the last cell of the table, I load a component dynamically using ComponentFactory. This loaded component is a dropdown menu. The problem arises when the dropdown menu is ...

The NestJS framework encountered an error due to a method being undefined in the

Encountering Error with NestJS Function create123: TypeError - Cannot read properties of undefined (reading 'create123') The constructor is displayed below \`export class AuthenticationService { constructor( private readonly usersServ ...

What is the best way to utilize a union of interfaces in TypeScript when working with instances?

Review this TypeScript snippet: class A {public name: string = 'A';} interface B {num: number;} class Foo { get mixed(): Array<A | B> { const result = []; for (var i = 0; i < 100; i ++) { result.push(Mat ...

Adding an event listener to the DOM through a service

In the current method of adding a DOM event handler, it is common to utilize Renderer2.listen() for cases where it needs to be done outside of a template. This technique seamlessly integrates with Directives and Components. However, if this same process i ...

Getting the button element in Angular when submitting a form

My web page contains multiple forms, each with a set of buttons. I want to incorporate a loading spinner on buttons after they are clicked. When using a regular click event, I am able to pass the button element: HTML <button #cancelButton class="butto ...

Aligning form elements horizontally with Angular 2 Material

Thank you in advance for taking the time to assist me. Your help means a lot! I have developed a form using Angular 2 Material Design and I am facing an issue with aligning two elements. Specifically, how can I align Bill Number and Year as shown in the s ...

Typescript throws an error when attempting to return an array of strings or undefined from a function

I created a shallow differences function that compares two arrays of strings and returns either undefined (if the arrays are different lengths) or a string array containing matching characters at corresponding indexes. If the characters don't match, i ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Create a custom definition for the useSelector function within a separate TypeScript file in a React

Question: Is it possible to define a type like <TRootState, string> in an external file and use it directly inside multiple Component files? External file: export type TUser = <TRootState, string> // This method does not work Component's ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Experience the latest happenings in SAP Spartacus 4.0 by signing up for updates directly from

I am facing an issue while trying to register an event in Spartacus import { Injectable } from '@angular/core'; import { CartDetailsComponent, PromotionService} from '@spartacus/storefront'; import { ActiveCartService, SelectiveCartServ ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

A guide on how to add the chosen item within the same tag using Angular 2

I am trying to choose an item and then add the same item within the same tag, similar to how tags are selected when asking a question on Stack Overflow. This is my template: <div class="form-group" *ngFor="let i of show"> <label for="examp ...

Verify if the array entries match

Within my select element, I populate options based on an array of values. For example: [{ name: 'A', type: 'a', }, { name: 'B', type: 'b', }, { name: 'B', type: 'b', }, { name: &apos ...

The multiline feature of tooltip on mat-table cell is malfunctioning

I adjusted the mat-tooltip to be displayed as multiline using the following style in the global CSS: .mat-tooltip-class-here { white-space: pre-line !important; } Interestingly, this formatting works on span and button elements but not on mat cells. ...