The *ngFor directive is displaying identical values

Is it possible to calculate the distance of each item while iterating through them?

Check out this Image for reference

In the code snippet below, the distance is retrieved using

(onResponse)="getDistance($event)"

  <div *ngFor="let routes of places[0].routes" class="todo-thumbnail-area">
    <agm-map [zoom]="1">
      <agm-direction [origin]="routes.origin" [destination]="routes.destination" (onResponse)="getDistance($event)">
      </agm-direction>
    </agm-map>
    <div class="todo-price">One Way Trip Cost - {{ this.routeTotalDistance }}</div>
  </div>

In Component.ts

  getDistance (event) {
    this.routeTotalDistance = event.routes[0].legs[0].distance.text;
  }

When I print the routeTotalDistance in the console, I notice that different values are shown for each iteration, but the final value is the same for all items.

It seems like after the last iteration, the routeTotalDistance is being set to the last iterated value. How can I resolve this issue? Your guidance would be appreciated.

Answer №1

It seems that the variable `routeTotalDistance` is being updated with the last iterated value in each iteration.

Indeed, whenever you invoke the `getDistance` function, the `routeTotalDistance` variable gets overwritten. One possible solution is to transform `routeTotalDistance` into an array:

<div *ngFor="let routes of places[0].routes; let i = index" class="todo-thumbnail-area">
<agm-map [zoom]="1">
  <agm-direction [origin]="routes.origin" [destination]="routes.destination" (onResponse)="getDistance($event, i)">
  </agm-direction>
</agm-map>
<div class="todo-price">One Way Trip Cost - {{ this.routeTotalDistances[i] }}</div>
routeTotalDistances: string[] = [];

...

getDistance (event, i) {
    this.routeTotalDistances[i] = event.routes[0].legs[0].distance.text;
}

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

Prevent the page from closing by implementing a solution within the ionViewWillLeave method

I'm looking to use the ionViewWillLeave method to prevent the page from closing and instead display a pop-up confirmation (using toast.service) without altering the form. ionViewWillLeave(){ this.toast.toastError('Do you want to save your cha ...

Having trouble deciding between flatMap and concatMap in rxJs?

Having trouble grasping the distinction between flatMap and concatMap in rxJs. The most enlightening explanation I found was on this Stack Overflow post about the difference between concatMap and flatMap So, I decided to experiment with it myself. import ...

Hierarchy-based state forwarding within React components

As I embark on the journey of learning Typescript+React in a professional environment, transitioning from working with technologies like CoffeeScript, Backbone, and Marionettejs, a question arises regarding the best approach to managing hierarchical views ...

The data type 'null' is not a valid index type to be used in the Array.reduce() accumulator

This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object? The initial objective was to merge numerous objects with various key-value pairs into a single nested object. For example, start ...

What is the process for displaying a custom component within a parent view component?

I am seeking to incorporate a custom component within mat-option. Below is the code snippet from my parent component: <mat-option *ngFor="let option of options" [value]="option.value"> HERE I WOULD LIKE TO INJECT SOME COMPONE ...

Can you explain the purpose of the GenericType parameter in a TypeScript promise declaration for me?

I am curious about whether the generic type in Typescript's Promise<GenericType> definition indicates the type of the object passed to the then handler. As an example, consider the following code: const pr:Promise<Array<Number>> ...

Exploring Angular2: Understanding how to retrieve an object with an unknown key

I am trying to showcase a specific value from different objects within a template. The path of the desired value depends on the object being referenced. For example: let obj = { "a": "a", "b": { "1": "1", "2": "READ ME" } } let ...

The system was expecting a stream but received a value of 'undefined'

I've been attempting to make chained http requests using Rxjs, but encountering a frustrating error... Error: Uncaught (in promise): TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, ...

"Slow loading times experienced with Nextjs Image component when integrated with a map

Why do the images load slowly on localhost when using map, but quickly when not using it? I've tried various props with the Image component, but none seem to solve this issue. However, if I refresh the page after all images have rendered once, they ...

``Engulfed in a sea of NgRx ViewModel

Apologies if this is unclear, there might be a fundamental aspect that I am overlooking, but here is my current issue: I am fetching a list of items from the backend, similar to: interface Item { id: number; userId: number; categoryId: number; } ...

What are the best practices for implementing ColdFusion Session Management in a Single Page Application?

I'm running an Angular 4 SPA on a server with ColdFusion 11. The application makes AJAX calls to .CFC files on the server for various functions. My goal is the following: When a user visits my Angular 4 app at myapp.mydomain.com, they will be redire ...

Using Angular to create an Echarts timeline that showcases 3 distinct categories

Here is an example graph created with Highcharts Struggling to replicate a chart like this using Echarts and ngx-echarts. Has anyone encountered this issue before? Currently utilizing the following dependencies: "@angular/animations": "^17 ...

Issues with updating table data when clicking the "Remove Selected" button a second time in Angular 8

Whenever I click the "Remove Selected" button on my table, the selected rows with checkboxes should be deleted. The issue is that it works perfectly fine the first time I click the button, but if I repeat the same steps (click the checkboxes and then click ...

The property slider in the d3 slider package is not found in the type 'types of d3'

I attempted to integrate a d3 slider into my d3 chart in Angular 2. I installed the d3slider package using the command: npm install --save @types/d3.slider. However, when trying to access the method "d3.slider()", an error occurred stating that "property ...

Specifying the type of "this" within the function body

After going through the typescript documentation, I came across an example that explains how to use type with this in a callback function. I am hoping someone can assist me in comprehending how this callback will operate. interface DB { filterUsers(fil ...

Angular 6 form validation for input fields

I have 3 input fields that are required, but I want to implement a logic where if one of them is filled, the other two should not be required anymore. I have managed to get this working, but the issue arises when I fill out the form and then remove the val ...

Create forms that can be dragged and drop to your desired location, with the ability to

I am trying to implement drag and drop functionality to this https://stackblitz.com/edit/angular-dynamic-survey-creation-golkhg project and save the data to a JSON file. I have been using Angular CDK but I am facing an issue with the following function: o ...

Leverage the TypeScript-generated controller within an Angular directive

I currently have an Angular controller that was generated using TypeScript: class FileManagerController { ... constructor($scope) { $scope.vm = this; ... } ...functions... } Can you guide me on how to integrate this controller i ...

Encountering a loader problem while trying to parse the ag-grid/angular.css file after upgrading to Angular 15

Encountered a build error when attempting to upgrade from Angular 14 to 15. Added the css loader, but unfortunately, it did not resolve the issue. ./node_modules/@ag-grid-community/styles/ag-grid.css?ngGlobalStyle:1:0 - Error: Module parse failed: Unexpec ...

Ensuring proper extension of Request headers in Typescript

I am having trouble retrieving the userId from req.headers, how can I fix this issue? Initially, I attempted the following: interface ISpot{ thumbnail: File, company: string, price: number, techs: string } interface IReqCustom<T& ...