Showing Arrays in Angular on HTML Page

I have created an array that stores multiple arrays with 3 indexes each. An example of the structure looks like this:

(3) [Array(3), Array(3), Array(3)]
0: (3) [199.4, 10.5, 19]
1: (3) [47.2, 2.1, 23]
2: (3) [133.6, 5.3, 25]

In my HTML, I want to display it in the following format:

Size: 199.4 
Size2: 10.5
Size 3: 19

This is how my HTML code looks:

<div [hidden]="isShowDiv" >
        <div class="list-group" *ngFor="let calculation of arr_name ">
            <a  class="list-group-item list-group-item-action" aria-current="true">
              <div class="d-flex w-100 justify-content-between">
                <h5 class="mb-1">{{arr_name}}</h5>             
              </div>
              
            </a>

Now, my question is, although I know I need to use

*ngFor="let calculation of arr_name ">
to iterate through the array size of 3, when I do so I get the following output:

199.4, 10.5, 19, 47.2, 2.1, 23, 133.6, 5.3, 25
199.4, 10.5, 19, 47.2, 2.1, 23, 133.6, 5.3, 25
199.4, 10.5, 19, 47.2, 2.1, 23, 133.6, 5.3, 25

I also understand that I can access individual values like {{arr_name[0][0]}} which displays 199.4, but since the array size may increase, I want a way to display all values dynamically. Is there a common approach for this?

This is my component.ts file:

import { Component, OnInit } from '@angular/core';
import { Position } from '../position';
import { Positions } from '../mock-positions';
import { Calculations } from '../mock-calculations';
import { Router } from '@angular/router';
import { Calc } from '../calc';

@Component({
  selector: 'app-create-position',
  templateUrl: './create-position.component.html',
  styleUrls: ['./create-position.component.css']
})
export class CreatePositionComponent implements OnInit  {

  isShowDiv = true;

  constructor(private router:Router) { }

  arr_name:number[][]=[]

  ngOnInit(): void {

  }

  calculate( ) {
    
      this.isShowDiv = !this.isShowDiv;
    
    this.sortArray()

  for(let i = 0; i < Positions.length - 1; i++) {


    //console.log(Positions[i].lat +" "+ Positions[i + 1].lat)

    var dy_ = 111.3 * (Positions[i].lat - Positions[i + 1].lat)

    var lat_ = (Positions[i].lat + Positions[i + 1].lat) / 2 * 0.01745

    var dx_ = 111.3 * Math.cos(lat_) * (Positions[i].lng - Positions[i + 1].lng)

    var distance_ = Math.sqrt(dx_ * dx_ + dy_ * dy_)

    var distance_ = distance_ * 1000 

    var distanceRounded: number =+distance_.toFixed(1);

    var startTime = Positions[i].time.toString()
    var endTime = Positions[i+1].time.toString()

    var starTimeCalc = new Date(startTime)
    var endTimeCalc = new Date(endTime)

    var sBetweenPos = endTimeCalc.valueOf() - starTimeCalc.valueOf();

    sBetweenPos= sBetweenPos * 0.001

    var duration = distanceRounded / sBetweenPos
    var durationRounded: number =+duration.toFixed(1)
  
    this.calc_.distanceRounded=distanceRounded
    this.calc_.durationRounded=durationRounded
    this.calc_.sBetweenPos=sBetweenPos

    this.arr_name.push([this.calc_.distanceRounded, this.calc_.durationRounded,this.calc_.sBetweenPos])

}

console.log(this.arr_name)

  }

}



Answer №1

If you need to access nested arrays, make sure to follow this structure:

<div *ngFor="let item of mainArray">
    <div *ngFor="let subItem of item.subItems; let i = index">
        Element {{ i }}: {{ subItem }}
    </div>
</div>

Consider moving your calculations logic into a dedicated service file for better organization.

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

"Encountering a module not found issue while trying to

Attempting to test out 3 node modules locally by updating their source locations in the package.json files. The modules in question are sdk, ng-widget-lib, and frontend. ng-widget-lib relies on sdk, while frontend depends on ng-widget-lib. To locally build ...

Invoke a function within an Angular component that is passed in as a parameter

Is it possible to invoke a function using a string in JavaScript? I have a scenario where I receive a string as the function name, and I need to call and run that function. However, my current code is not working as expected. Below is the code snippet I ...

Utilizing Glassfish Application Server and MSSQL Database for Angular Front-End Authentication in Jakarta

Embarking on my journey in the realm of web development, I am eager to implement authentication for my full-stack application. Armed with Angular 13 on the front end, Jakarta 9 running on Glassfish app server, and MSSQL database, I find myself at a loss on ...

Optimal strategies for managing server-side validation/errors in Angular applications

Back in the day, I used to retrieve HTTP responses with a TypeScript object. validateTokenHttp(token: string): Observable<User> { return this.http.get<User>(`${environment.api}/auth/verifyToken/${token}`); } Sometimes it would return a Us ...

Extracting data from response body in Angular after encountering 403 error during HTTP Post request

I am currently working on an Angular 9 project where I handle login functionality using HTTP post and HttpClient. In case of a failed login attempt, the server responds with HTTP status code 403 and a JSON object containing the error message that needs to ...

Tips on switching the default camera with ngx-scanner-qrcode library in Angular

In my current project, I am utilizing the ngx-sanner-qrcode library for QRCode scanning. However, I am interested in changing the default camera from front to back in order to enhance the user experience. I assumed that I could change the default camera b ...

What is the best way to rekindle the d3 force simulation within React's StrictMode?

Creating an interactive force directed graph in React using D3 has been successful except for the dragging functionality not working in React StrictMode. The issue seems to be related to mounting and remounting components in ReactStrict mode 18, but pinpoi ...

Switching between two distinct templateUrls within an Angular 6 component

When working with Angular 6, we are faced with having two different templates (.html) for each component, and the need to change them based on the deployment environment. We are currently exploring the best practices for accomplishing this task. Some pos ...

Angular 2 radio button problem with model-driven form

I'm facing a challenge with getting radio buttons to function correctly in my reactive form. Below is the code for my component: export class SettingsFormComponent implements OnInit { public sForm: FormGroup; public submitted: boolean; d ...

Typescript: The type 'T' fails to meet the requirement of being an 'object'

Ever since I installed a package along with its @types package, I've been encountering an issue with the following code: https://i.stack.imgur.com/rrRhW.png This is the error message that I'm receiving: https://i.stack.imgur.com/BfNmP.png The ...

Tips for preventing the error message "The property 'map' is not present on type 'string | string[]'."

I received an error message stating Property 'map' does not exist on type 'string | string[]': const data = [ ['1', ['11']], ['2', ['21']], ['3', ['31']], ] data.map(top ...

Strategies for redirecting search queries when adding a new path

Issue I am facing a challenge with pushing a new path to the URI while maintaining existing search queries. For example: Current URL: https://example.com/foo?bar=123&foobar=123 When I use history.push('newPath'), I end up with https://exa ...

The user interface in Angular 7 does not reflect the updated values after subscribing

Upon examining the code provided, it is evident that the UI does not reflect the updated value even though the field is set correctly. I have attempted two different approaches but have not explored the change detection approach as I believe the current c ...

AWS Alert: Mismatch in parameter type and schema type detected (Service: DynamoDb, Status Code: 400)

Upon trying to log into my development Angular system, I encountered the following error. My setup involves AWS Serverless, Amplify Cognito, and Graphql. An error occurred: One or more parameter values were invalid. Condition parameter type does not ma ...

Tips for improving the performance of your Ionic 2 app

Recently, I've been working on enhancing the performance of my Ionic 2 App, particularly focusing on optimizing page loading speed. After closely analyzing the timeline of page transitions using Chrome Dev Tools, it became evident that the bottleneck ...

Unlocking the power of URL manipulation in Fastify using Node.js

I'm attempting to retrieve specific parts of the URL from a Fastify server. For instance, the URL looks like this: http://localhost:300/query_tile/10/544/336 Within the Fastify server, I need the values for z/x/y. I've attempted the following ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...

After calling the PHP API, the http.get method in Ionic 2 is returning a value of isTr

Even though a similar question has been posted before, I am still puzzled about why I am receiving: 'isTrusted': true every time I call a PHP API from Ionic 2. The code I am using is as follows: getProduct(id: string){ if(this._product){ con ...

Is it possible to view the original source code by simply clicking ctrl + click?

Currently, I am working on a project involving TypeScript and Angular, utilizing the library Spartacus. Often times, I find myself needing to reference the source code. This is how I currently go about it: I come across StateUtil from @spartacus/core, th ...

How can I dynamically update the sidebar in Ionic 3 post-login without the need to reload the app or refresh the browser?

I have successfully implemented login and sign up functionality in my ionic 3 app. However, I am facing an issue where the username is not updating in the sidebar instantly after logging in. Currently, I need to refresh the browser or close and reopen the ...