When using ngFor in HTML, the ID of an object within an array of objects can become undefined during execution

Currently, I am in the process of developing a mobile application with the Ionic framework. One of the key functionalities of this app involves making an API call to retrieve transaction data, which then needs to be displayed in the HTML template:

The data returned by the API looks something like this:

[
    {
        amount1:"100",
        buyer_email:null,
        buyer_name:"test",
        confirms_needed:2,
        created_at:"2018-07-09 07:56:33",
        id:8,
        invoice:null,
        currency1: "USD"
    },
    {
        amount1:"100",
        buyer_email:null,
        buyer_name:"test",
        confirms_needed:2,
        created_at:"2018-07-10 04:36:33",
        id:6,
        invoice:null,
        currency1: "USD"
    }
]

Here is the TypeScript code responsible for making the API call:

 ionViewDidLoad() {
    this.transactionProvider.getTransactions()
    .subscribe((data:any)=>{
      this.transactions = data;
      console.log(this.transactions);
    },error=>{
      console.log(error);
    });
  }

To initialize the transactions, I simply declare 'transactions' under the export class.

This is how I loop through the transaction data in my code:

<div class="width-100p  fl-left box-shadow   border-radius-10 padd-tp-bt-10 mg-tp-20" *ngFor="let transaction of transactions">
    <div (click)="saveTransactionClick(transaction)">
        <img width="20" src="assets/imgs/currencies/icons/{{transaction.currency1}}.png">
        <div class="fl-left mg-l-10">
            <div class="f-size-12 width-100p fl-left">{{transaction.currency1}} text: {{transaction.id}} :tet</div>
            <div class="f-size-10 width-100p fl-left gray">{{transaction.created_at | date: 'yyyy-MM-dd'}}</div>
            <div class="f-size-10 width-100p fl-left gray">{{transaction.created_at | date: 'hh:mm:ss'}}</div>
        </div>
    </div>
</div>

However, I am facing an issue where when I console.log(this.transactions), the ID is showing up as undefined, even though the other data (amount, buyer_name, etc.) is correct.

If I remove the ngFor loop from the HTML, the IDs return to normal.

I'm puzzled as to why this is happening and I'm unsure how to resolve it. Any insights would be greatly appreciated. Thank you.


Update

The issue was caused by incorrect usage of ngIf

I discovered that I had mistakenly used ngIf incorrectly in my HTML code. I had written

*ngIf="transaction.id = clickedTransactionId"
, and upon correcting it to
*ngIf="transaction.id == clickedTransactionId"
, the problem was resolved.

Thank you for your assistance.

Answer №1

A few days back, I made a mistake in my ngIf statement where I was assigning the id instead of checking its value

*ngIf="transaction.id = clickedTransactionId"

After correcting it to

*ngIf="transaction.id == clickedTransactionId"

everything started working correctly. Huge thanks to everyone who helped!

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

Angular2's service executing http method is limited to just once

I have a service that is responsible for retrieving information from the server. The goal is to execute the request only once and then share the data with every component in the application. Currently, my code looks like this: @Injectable() export class P ...

A guide to identifying a user's browser type using server-side code (Node.js) when making an API request

Can someone help me differentiate between REST API calls made from a desktop browser and those from a mobile browser, specifically tablets? I am currently using Node Express on my server side. ...

Extracting and transforming an array into a list with the desired outcome

Looking for a way to flatten the array below into a single line array using Typescript/JavaScript? Student: any = [ { "id": "1", "name": "Jhon", "Marks": { "Math": "90", "English": "80", "Science": "70" } }, { "id": "2", "name": "Peter", "Marks": { "M ...

I aim to link a variable in a directive with a component

Each directive comes with its own functionality and specific features. It can be challenging to understand how to connect a variable from a directive to a component. This particular directive involves detecting x-axis and y-axis positions during mouse ev ...

An array of objects can be used as input for the autocompleteItems in ngx-chips

Recently, I've been exploring the use of Angular 4 ngx-chips for input tags and came across an interesting issue. While looking at the documentation on ngx-chips, I noticed a problem with using an array of objects as input for 'autocompleteitems& ...

I've been stuck for hours, is there anything I should include?

I'm attempting to access http://localhost:4200/Personnes/view/:2, but I encountered the following error (ERROR TypeError: Cannot read property 'nom' of undefined) "My personnnes.service.component.ts" `export class PersonnesService { baseUr ...

next.js users may encounter a problem with react-table not rendering correctly

Encountering difficulties while attempting to integrate a basic table function into my upcoming application. Despite being a sample output, the function fails to load into the index for some unknown reason! // Layouts import Layout from "../components ...

Exploring nested JSON objects within an array using ngFor directive

My application uses Angular 6 and Firebase. I am trying to showcase a list of all appointments. Below is my approach: service.ts getRDV() { this.rdvList = this.firebase.list('/rdv'); return this.rdvList; } Model: export class RDV { key: ...

Generate a 2D matrix to represent a grid

I have a list of numbers that I need to convert into a two-dimensional array. For example: let data=['1','4','2','1','6','9','1','5',] The desired output would be: result = ...

Finding the perfect pairing: How to align counters with objects?

public counter = 0; x0: any; x1: any; x2: any; x3: any; x4: any; next(){ this.counter += 1; this.storage.set("Count", this.counter); console.log(this.counter); this.logic(); } logic(){ //automatic counter here var xNum = JSON.parse(JSON.stri ...

Arranging mat-checkboxes in a vertical stack inside a mat-grid-tile component of a mat-grid-list

I'm looking to create a grid list with 2 columns, each containing 2 checkboxes stacked vertically. While I found this helpful question, it still involves a lot of nested divs. Is there a cleaner way to achieve this layout? Here's how I currentl ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

Guide to inheriting functions from a parent component in Angular 2

Hello, I am a beginner in the realm of angular2 and would appreciate any assistance in refining my vocabulary and terminology. Currently, I have a class that consists of two directives structured as follows: In parent.component.ts, the Parent component i ...

Is there a way to restrict props.children.some to only accept image types?

Currently troubleshooting the following issue: An error is occurring: 'Property 'type' does not exist on type 'true | ReactChild | ReactFragment | ReactPortal'. Property 'type' does not exist on type 'string'. ...

What is the best way to simulate an ActivatedRouteSnapshot?

Currently, I am working on unit testing the code snippet below: ngOnInit() { this.router.events.subscribe((val) => { if (val instanceof ActivationEnd && val.snapshot) { this.selectedLanguageCode = val.snapshot.queryParams ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Comparison of valueChanges between ReactiveForms in the dom and component级主动形

Is there a method to determine if the change in valueChanges for a FormControl was initiated by the dom or the component itself? I have a scenario where I need to execute stuff() when the user modifies the value, but I want to avoid executing it if the v ...

How to showcase ByteArrayContent using Angular

I have a Web API that has been functioning well for two years in existing Knockout and polymer applications, so I don't want to make any changes to it. Now, I am trying to integrate Angular and need to display an image from the API. Below is the code ...

What is the purpose of `{ _?:never }` in programming?

I've been going through some TypeScript code and I stumbled upon a question. In the following snippet: type LiteralUnion<T extends U, U extends Primitive> = | T | (U & { _?: never }); Can anyone explain what LiteralUnion does and clarif ...

Tips for resolving type inference for a component variable in a jest Mount test created using reactjs

I am currently working on a React project that is built in Typescript, specifically dealing with a unit test involving the use of mount from Enzyme. As I strive to align the project with the tsconfig parameter "noImplicitAny": true, I am faced with the cha ...