Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this:

<div *ngIf="chat.asReceiver.id != user?.id; else otherParty">

Unfortunately, it always returns the following error:

ERROR TypeError: Cannot read property 'id' of undefined

After confirming that both chat.asReceiver.id and user?.id have values, I tried nesting my div under another *ngIf condition like so:

<div *ngIf="user">
   <div *ngIf="chat.asReceiver.id != user?.id; else otherParty">
      //....
   </div>
</div>

However, the error persists.

component

public user: User;
chats: any[] = [];

constructor( ) {
    this.getChats();
}

ionViewWillEnter() {
    this.authService.user().subscribe(
      user => {
        this.user = user;
      }
    );
}

getChats() {
    this.privateChatService.getChats().subscribe((res) => {
      for (const chat of res.data) {
        this.chats.push(chat);
      }
    });
}

Any suggestions on how to resolve this issue?

Update

This is how my data looks:

Update 2

<div *ngIf="chats.length>0">
    <ion-item-sliding *ngFor="let chat of chats; index as indexOfelement;">
        <div *ngIf="chat.asReceiver.id != user?.id; else otherParty">
            <ion-item class="chat-groups">
                <ion-avatar slot="start">
                <div *ngIf="chat.asReceiver.photo != null; else placeholderImage">
                    <img (click)="openImageRes(chat)" class="gImage" routerDirection="forward" [src]="chat.asReceiver.photo">
                </div>
                <ng-template #placeholderImage>
                    <img routerDirection="forward" class="gImage" src="../../assets/placeholders/avatar.jpg">
                </ng-template>
                </ion-avatar>
                <ion-label routerDirection="forward" [routerLink]="['/tabs/', 'chat', chat.id]">
                    <h2 style="float: left;width: 80%;"slot="start" [innerHTML]="chat.asReceiver.username"></h2>
                    <ion-badge slot="end" color="primary">{{totalBadges}}</ion-badge>
                </ion-label>
            </ion-item>
        </div>
    </ion-item-sliding>
  </div>

Answer №1

It appears that the issue lies with the absence of the asReceiver property within the chat object. Your code snippet lacks the definition of the chat object; could you please include it as well? Without a clear understanding of its structure, consider adding question marks to the ngIf condition for the chat object.

<div *ngIf="chat?.asReceiver?.id !== user?.id; else otherParty">

Another concern is that the current setup leads to triggering the else statement when both IDs are undefined, not just when they match.

Answer №2

Perhaps consider implementing something similar to this:

<div *ngIf="(conversation && conversation.asSender &&& user) && (conversation.asSender.id !== user?.id); else alternateParty">

In addition, I recommend converting all of the code to utilize async pipes for better efficiency.

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

Executing multiple http post requests in Angular2 using a for loop

I've encountered an issue while attempting to upload multiple files with individual titles. The problem arises when sending requests to the server, as I'm trying to pass each file and its corresponding title one by one. I have an array called bin ...

Using Typescript in a definition file requires classes and interfaces to be included in the compiled .js file

I am currently working on a Typescript project that consists of two crucial files: app.ts models.d.ts The initial lines of code in app.ts are as follows: ///<reference path="models.d.ts"/> 'use strict'; import * as fs from 'async-f ...

What could be the reason behind the error related to react-router-dom?

index.tsx import React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; const root = ReactDOM.createRoot( document.getElementById('root') as HTMLElement ); root.render( <React.S ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Is it possible for TypeScript to automatically determine the type of an imported module based on its path?

I'm currently working on creating a function, test.isolated(), which wraps around jest.isolateModules. This function takes an array of strings representing the modules to be imported, along with the usual arguments (name, fn, timeout), and then inject ...

Having difficulty implementing a versatile helper using Typescript in a React application

Setting up a generic for a Text Input helper has been quite challenging for me. I encountered an error when the Helper is used (specifically on the e passed to props.handleChange) <TextInput hiddenLabel={true} name={`${id}-number`} labelText=" ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

Is Error k originating from Angular or Electron?

While utilizing Angular 10 in my Electron application, I encountered some errors after building a release version of the app. These errors are visible in the Chrome Inspector, but it's unclear whether they stem from Electron or Angular, and the messag ...

Error: Invalid connection string for ELF Lambda detected

Having an issue with a lambda function that connects to a remote MongoDB on an EC2 instance using TypeScript. While I can connect to the database locally, there is an ELF error when running in lambda. It seems to be related to mismatched binaries of npm pa ...

Merging Two JSON Objects into a Single Object Using Angular 4-6

Two JSONs are available: The first one (with a length of 200): {date_end: "2099-12-31", id: "2341"} {date_end: "2099-12-31" id: "2342"} ... The second one (length 200): {type: "free", discount:"none", warranty: "yes"} {type: "free", discount:"none", ...

Delaying the tap after emitting an action in the Ngrx store

Within the realm of Ngrx store, I am currently utilizing 2 effects: @Effect({ dispatch: false }) toastSuccess$ = this.actions$ .pipe( ofType(TOAST_SUCCESS), map((action: any) => this.toastr.success(action.payload, &a ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

I'm having trouble asynchronously adding a row to a table using the @angular/material:table schematic

Having trouble asynchronously adding rows using the @angular/material:table schematic. Despite calling this.table.renderRows(), the new rows are not displayed correctly. The "works" part is added to the table, reflecting in the paginator, but the asynchron ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Angular 2: Implementing service functions on button click using the (click) event

Is it possible to call a function from my service when clicking on an element in the HTML returned from an HTTP call? Here is the HTML snippet: <a (click)="SellingVarietiesService.goToVarietyDetails(3)">Test</a> The function I want to call i ...

Unlocking the Secrets of Passing ID Parameters Between Pages and Fetching Data from External APIs in Ionic 4

Before I get into it, apologies for the basic question, but I'm struggling to figure this out. Here's my issue: I have a list of categories that are being fetched from a nodeJS api. My goal is to fetch the subcategories based on the id from the d ...

What is the best way to bring attention to a field that is outside the current viewport?

Is there a way to automatically scroll to the specific invalid field after clicking on submit in a large form, without having to manually search for it by scrolling through the page? ...

Ways to eliminate the lower boundary of Input text

Currently, I am working on a project using Angular2 with Materialize. I have customized the style for the text input, but I am facing an issue where I can't remove the bottom line when the user selects the input field. You can view the red line in t ...