Discovering how to display the hidden messages section in the absence of any ongoing chats with the help of angular2

I currently have 2 tabs set up on my page.

  1. The active messages tab is functioning perfectly without any issues.
  2. However, I am encountering an error with the closed messages tab. If there are no messages in this tab, the system displays an error message which seems to be caused by a front-end looping issue.

Could someone please assist me in resolving this problem? I would like the closed tab to display an empty field when there are no conversations present. Additionally, it should function properly even when switching between tabs.

Below is the HTML code snippet:

<ul>
        <li *ngFor="let reply of message_close.messages">
          <img [src]="reply.from_user_image || '../assets/images/msg.png'"/>
          <p><b>{{reply.name}} </b> <span> {{reply.updated_at | date:'dd.MM.yyyy'}} - {{reply.updated_at | date:'h:mm'}}</span></p>
          <p>{{reply.text}}</p>
        </li>
      </ul>

And here is the TypeScript code snippet:

loadMessages() {
    this.service
          .getMessages()
          .subscribe(
            data => {
              this.messagesdata = data;
              this.activeMessages = data.filter(msg => msg.active == true && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0)
              this.closedMessages = data.filter(msg => msg.active == false && msg.from_user_name !== 'Anonymus' && msg.messages.length > 0);
              if (this.closedMessages.length > 0) {
                if(!this.message_close) {
                  var test2 = this.message_close = this.closedMessages[0];
                  this.message_idc = this.closedMessages[0].id;
                  this.message_close.messages.map(function(msg) {
                    if(msg.from_user_id == test2.from_user_id) {
                      msg.from_user_image = test2.from_user_image;
                    } else {
                      msg.from_user_image = test2.to_user_image;
                    }
                    if(msg.to_user_id == test2.to_user_id) {
                      msg.to_user_image = test2.to_user_image;
                    } else {
                      msg.to_user_image = test2.to_user_image;
                    }
                  })
                }
              }              
            },error => {});
  }

Answer №1

To achieve this, you can utilize the ngIf directive.

    <ul>
       <li *ngIf="message_close == undefined || message_close.messages.length == 0|| message_close.messages.length == undefined">
          <p>No closed messages are available.</p>
         </li>

        <li *ngFor="let reply of message_close.messages" >
          <img [src]="reply.from_user_image || '../assets/images/msg.png'"/>
          <p><b>{{reply.name}} </b> <span> {{reply.updated_at | date:'dd.MM.yyyy'}} - {{reply.updated_at | date:'h:mm'}}</span></p>
          <p>{{reply.text}}</p>
        </li>

      </ul>

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

Ensuring a precise data type in a class or object using TypeScript

I am familiar with Record and Pick, but I struggle to grasp their proper usage. My goal is to ensure that a class or object contains specific data types such as strings, Booleans, arrays, etc., while also requiring properties or fields of Function type. in ...

Error Encountered During Angular Production Build: Plugin "proposal-numeric-separator" Not Found

After trying to build the production version, I encountered an error message stating that Could not find plugin "proposal-numeric-separator". Ensure there is an entry in ./available-plugins.js for it.. Please refer to the screenshot of the error attached b ...

Having trouble with Angular 2 and Ionic2 mocks? Getting an error message that says "No provider

Currently in the process of creating a spec.ts file for my application. The challenge I'm facing is related to using the LoadingController from ionic-angular. In order to configure the module, it requires providing the LoadingController (due to its pr ...

Error: Attempting to access properties of an undefined value while retrieving data from Firebase

Struggling with displaying data in my NextJS app. Data is being fetched from Firebase, and the interface structure is as follows: export default interface IUser { name: string; email: string; uid: string; profileImageURL: string; publicData: { ...

Is the return value a result of destructuring?

function display(): (number, string) { return {1,'my'} } The code above is displaying an error. I was hoping to use const {num, my} = print(). How can I correctly specify the return type? ...

Is there a way to divide v-progress linear into 4 pieces in Vuejs, or are there alternative design options for achieving this in Vuetify 2?

I have set up a table in Vuetify 2 with a v-progress-linear component to monitor the user's remaining time. Initially, my implementation was simple like this. However, we decided to split it into 4 sections for better visibility of the user's ti ...

Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format: text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] m ...

Is it possible to deduce Typescript argument types for a specific implementation that has multiple overloaded signatures?

My call method has two signatures and a single implementation: call<T extends CallChannel, TArgs extends CallParameters[T]>(channel: T, ...args: TArgs): ReturnType<CallListener<T>>; call<T extends SharedChannel, TArgs extends SharedPar ...

Exploring TypeScript's Index Types: Introduction to Enforcing Constraints on T[K]

In typescript, we can utilize index types to perform operations on specific properties: interface Sample { title: string; creationDate: Date; } function manipulateProperty<T, K extends keyof T>(obj: T, propName: K): void { obj[propName] ...

Multiple values are found in the 'Access-Control-Allow-Origin' header in Angular 7

After serving my Angular app on port 4202, I attempted to connect to a remote Spring MVC app using the code snippet below. this.http.post<Hero[]>('http://localhost:8080/api/hero/list', {"id":1}, httpOptions) However, I encountered the fol ...

Encountering a service error that results in the inability to read properties of undefined when passing a method as a

Whenever I attempt to pass a service function as a parameter to another function, an error 'Cannot read properties of undefined myService' occurs during execution. However, calling this.myService.method() individually works perfectly fine without ...

TS - Custom API hook for making multiple API requests - incompatible type with 'IUseApiHook'

What is my objective? I aim to develop a versatile function capable of handling any type of API request for a frontend application. Essentially, I want to add some flair. Issue at hand? I find myself overwhelmed and in need of a fresh perspective to revi ...

Extract data from Angular2 class

I am having trouble with the data binding of {{value}}. Here is a straightforward example: app.component.ts import {Component, OnInit} from "@angular/core"; @Component({ selector: "app", templateUrl: "./app/app.html" }) ...

Steps to disable TypeScript error messages for unused variables

I encountered an issue in my Angular CLI that says: jest.config.js is part of the TypeScript compilation but it's unused. Add only entry points to the 'files' or 'include' properties in your tsconfig. Additionally, I have a few o ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

Combining Data in Angular and Firestore: Exploring the Power of Observables

I am attempting to retrieve a profile document using valueChanges and combine it with session data. However, when I utilize forEach, the observable returned is null (I'm still new to both technologies). The following code successfully re ...

Is there a way to programmatically activate the iOS unavailable screen?

Is there a way to programmatically simulate the iPhone unavailable screen after entering the wrong password multiple times, with a specific time delay? I am searching for an API that can remotely lock my iPhone screen so that it cannot be unlocked by me. ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

Tips on preventing the need for null or undefined checks in JS/Typescript singletons that have an initialization function

Is there a way to streamline the process of handling props in an Object literal that is dynamically initialized only once? I'm looking for a pattern that would eliminate the need for repetitive null/undefined checks and throw errors when certain metho ...