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

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Tips for Safely Utilizing localStorage in Angular

When dealing with easily changeable localStorage data, how can access controls and security be improved in an Angular App? Imagine if our localStorage contains: data - {name:user, account_status:inactive,...} It is concerning that a user could effortl ...

Unable to confirm the version of Angular

I am currently using node version 10.14.1 and npm version 6.4.1 with angular version 7.0.3 installed. However, when I try to check the angular version by running the ng --version command, I encounter an error message in the command prompt. C:\Users&b ...

We're sorry, the request was blocked due to a missing Access-Control-Allow-Origin header

Recently, while working on a blog application with the front end in react + typescript and backend in go iris, I encountered an issue when trying to fetch blog content using a get request. The backend was running on localhost:5000 and the node at localhost ...

Inheritance-based type inference

I have created a class hierarchy to manage inheritance in my code. Here is an example of how it looks: class A { clone(): A { return new A() } methodA() { return this.clone() } } class B extends A { clone(): B{ return new B() } ...

Incorporate a dropdown selection option into a clickable Angular 6 table row using Bootstrap 4 styling

I am currently updating a financial account book that displays all available accounts in a table format. Each row provides essential details about a specific account, and when a user clicks on a row, Angular redirects them to a detailed view for that parti ...

Issue: Incompatibility between React and TypeScript leading to an error message - "No

When I try to map through an array in my code, I encounter a significant error as shown below: // Home.tsx render() { const { inputs, outputs, expectedOutputs } = this.state; return ( <ContentContainer> {inputs.map((inpu ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Subscribing and updating simultaneously will not function. Whichever action is attempted, the other will result in an error, and the

import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams } from 'ionic-angular'; import {AngularFireDatabase, AngularFireObject} from 'angularfire2/database'; import{ShoppingItem} ...

What is the recommended approach for storing and retrieving images in the Angular 5 framework?

I have an Angular 5 app that utilizes Java rest services. The Java application stores images in a folder located outside of the Java app itself. Now, my goal is for the Angular app to be able to read these images. Although it makes sense to store them outs ...

Incorporating aws-sdk into Angular 2 for enhanced functionality

I'm currently working on integrating my Angular2 application with an s3 bucket on my AWS account for reading and writing data. In the past, we used the aws-sdk in AngularJS (and most other projects), so I assumed that the same would apply to Angular2 ...

Initializing variables in Angular2 templates

I am facing an issue where, upon running the application, the console displays all the logs from the ngOnInit function, but the actual view only shows a skeleton without the component variables and text from l18n. It seems like the ngOnInit is not working ...

Utilizing REST-API with Angular 2 and Electron

I am encountering an issue with my Electron App that utilizes Angular 2. I had to make a modification from <base href="/"> to <base href="./">, which is a relative path within the file system, in order to make it function properly. However, thi ...

A step-by-step guide on reversing options in the Ant Design Cascader component

By default, the Cascader component's options are nested from left to right. I am looking to have them go from right to left instead. However, I could not find anything in the component's API that allows for this customization. Is it even possibl ...

Issue encountered while executing jest tests - unable to read runtime.json file

I've written multiple unit tests, and they all seem to pass except for one specific spec file that is causing the following error: Test suite failed to run The configuration file /Users/dfaizulaev/Documents/projectname/config/runtime.json cannot be r ...

Learn how to selectively hide the header from the root layout on a single page in Next.js version 14

I am currently working on an app using Next.js 14 and TypeScript. In my root layout, I have added a header and footer. However, on one of the pages I created, I need to hide the header and footer. import type { Metadata } from "next"; import { In ...

How can I retrieve image files from locations outside the Angular 5 app or assets directory?

One of the features in my app allows users to upload images. I recently learned that it's best practice to store these image files outside of the app or assets folder since those folders are compiled. Here is a snapshot of my app's folder structu ...

Steps to display a modal within an inactive tab:

I have been using ngx-bootstrap tabset, although I believe this issue could apply to all bootstrap tabs as well. <tabset> <tab class='active'> <angular-modal-component> </angular-modal-component> </tab> <tab> & ...

Define an object type in Typescript that includes both specified properties and an unlimited number of unspecified properties

I'm attempting to create a custom data type using the code below, but it's not working: type CustomDataType { [key: string]: CustomDataType; isValid: boolean; errors?: string[]; } My goal is to have a CustomDataType with an isValid propert ...

The production build of Angular 2 with special effects amplification

I am currently working on an Angular 2 Beta 8 app that I need to bundle and minify for production deployment. Despite configuring the system to generate a Single File eXecutable (SFX) bundle, I am encountering issues with creating a minified version of the ...