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

Angular 13: How to Handle an Empty FormData Object When Uploading Multiple Images

I attempted to upload multiple images using "angular 13", but I'm unable to retrieve the uploaded file in the payload. The formData appears empty in the console. Any suggestions on how to resolve this issue? Here is the HTML code: <form [formGro ...

Developing Angular 2 custom async validators for use in reactive forms

I am currently working on a reactive form that requires unique form controls: this.form = new FormGroup({ name: new FormControl(this.initialValue, [ Validators.required, ], this._uniqueNameValidator.bind(this)), }); To achieve this, I have create ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

React - A high-capacity file selector component designed to efficiently handle large numbers of files being selected

I am in search of a component that can retrieve a list of files from the user without actually uploading them. The upload functionality is already in place; I simply require a list of selected files. The component must meet the following criteria: Restric ...

Discovering the tab index of a tab header in Angular 4 Material

In my Angular application, I am using a mat-tab component to display tabs dynamically generated from an array. The template looks something like this: <mat-tab-group> <mat-tab *ngFor="let tb of dynTabs"> ...

Encountering a Problem with HTTP Requests in Angular 2

Seeking assistance with a technical issue. My objective: Make a REST API call to retrieve JSON data and resolve an Angular 2 promise. ServerAPI built with Node.js/ExpressJS/Lodash Sample of server.js file: var express = require('express'); va ...

What function is missing from the equation?

I am encountering an issue with an object of type "user" that is supposed to have a function called "getPermission()". While running my Angular 7 application, I am getting the error message "TypeError: this.user.getPermission is not a function". Here is w ...

Organize items within an array based on dual properties rather than a single one

Here is an array of objects that I would like to group based on certain keys (JSON format): [ { "name": "john", "lastName": "doe", "gender": "male" }, { "name": &qu ...

Styling with CSS: The Art of Showcasing Initials or Images of Individuals

By following this elegant HTML and CSS example, I am able to showcase my initials over my photo. While this is wonderful, I would like the initials to be displayed only if the image does not exist; if the image is present, the person's initials shoul ...

Creating dynamic Angular Material 2 MatMenu instances with ease

Currently, I am looking to dynamically generate multiple MatMenu components. However, I am unsure about the following: 1 - How can I dynamically create a template reference variable for the mat-menu component? 2 - How do I reference the dynamically creat ...

"An issue has been noticed with Discord.js and Discordx VoiceStateUpdate where the return

Whenever I attempt to retrieve the user ID, channel, and other information, I receive a response of undefined instead of the actual data import { VoiceState } from "discord.js"; import { Discord, On } from "discordx"; @Discord() export ...

Mastering Vue3: Typed Component Instance Template Refs with Exposed Methods

In my project, I am working with a component called A that has a method called send. Here is an example of how Component A is structured in A.vue: <script setup lang="ts"> function send(data: string) { console.log(data) } defineExpose({ ...

What is the process of hosting an Angular application on a pre-existing Node.js server?

I am currently working on an Angular 6 application that communicates with an existing Node.js API application. Up to this point, I have been using the following command to run and build my Angular application: ng serve Now, I am interested in serving m ...

How to set return types when converting an Array to a dynamic key Object in Typescript?

Can you guide me on defining the return type for this function? function mapArrayToObjByKeys(range: [string, string], keys: { start: string; end: string }) { return { [keys.start]: range[0], [keys.end]: range[1] } } For instance: mapArrayToObj ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

How is it that in TypeScript, a potential numeric value in an interface can be transformed into an impossible numeric value in a class implementation?

Encountered a surprising behavior from the TypeScript compiler today. Unsure if it's a bug or intentional feature. If it is indeed intentional, I would like to understand the reasoning behind it. The issue arises when declaring an interface method wi ...

Establish a default value for cascading Angular dropdowns

In my JSON data, each country has an ID associated with it. I am trying to set the default value of a select option to 'selected' based on a specific ID (in this case, 100). Here is the code for my select element: <select (change)="onNational ...

Navigating away from a guard in a module federated Angular application

My Angular application uses module federation with a route-guard that redirects to another route. Everything works fine when run as a standalone application, but I encounter an error when it is integrated into a shell application. The error states that the ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

Assigning values to objects based on the types of their properties in Typescript

In my Redux store, I want to create a reducer that can modify any attribute values within the store. Consider the state object defined with specific types: type StoreState = { admins: Admin[]; messages: Message[]; pageInformation: PageInformation; } ...