Guide to displaying elements from an array using Angular

Embarking on the journey of learning Angular has been quite a challenge for me. One specific difficulty I've encountered is extracting an item from an array and displaying it in the corresponding HTML file within that component. The snippet below illustrates the onClick function in the bill-item.component.ts file:

arr: Array<any> =[];
itemArray: Array<any> =[]; 

     onAddToBill(itemId:string, name:string , expireDate:string , quantity:string){

      this.itemArray.push([itemId,name,expireDate,quantity]);
      this.arr.push(this.itemArray);
      console.log(this.arr);

      }

I'm looking to showcase the item array in my bill-item.component.html, which is depicted below:

                 <tbody>

                  <tr *ngFor="let itemArrays of arr">

                    <td *ngFor="let obj of itemArrays">{{obj[1]}}</td>
                    <td *ngFor="let obj of itemArrays">{{obj[0]}}</td>
                    <td><input type="number" class="is-center" id="number" value="1" style="width: 50%;" /></td>
                    <td *ngFor="let obj of itemArrays">{{obj[2]}}</td>
                    <td *ngFor="let obj of itemArrays">{{obj[3]}}</td>

                  </tr>

                </tbody>

The initial item list appearance after adding the first item can be seen in the following image:

https://i.sstatic.net/LoUt9.png

However, upon adding a second item, the layout of the item list shifts as shown in this image https://i.sstatic.net/D1YTG.png

All the items are being consolidated into the same row, when what I desire is each item to be displayed on a separate line.

In an attempt to achieve the desired display, I tried the code snippet below:

           <tbody>
              <tr *ngFor="let entries of arr">
                <td>{{entries [1]}}</td>
                <td>{{entries [0]}}</td>
                <td><input type="number" class="is-center" id="number" value="1" style="width: 50%;" /></td>
                <td>{{entries [2]}}</td>
                <td>{{entries [3]}}</td>
              </tr>
            </tbody>

https://i.sstatic.net/nOeWk.png

However, the result was not as expected. The ID corresponds to entry[0], resulting in all instances of the array populating that field.

The screenshot below displays the output of console.log(arr) after adding 3 items: https://i.sstatic.net/uj0sw.png

https://i.sstatic.net/m4D0I.png

Answer №1

Instead of using "arr" to retrieve item details, it is more efficient to directly access values from the "itemArray" and display them in a table format.

<table>
      <tr *ngFor="let x of itemArray">
          <td>{{x[0]}}</td>
          <td>{{x[1]}}</td>
      </tr>
</table>

This approach simplifies the process and enhances readability.

Answer №2

Instead of using *ngFor for each entry, you can directly access array indexes like entries[1]

            <tbody>
              <tr *ngFor="let entries of arr">
                <td>{{entries [1]}}</td>
                <td>{{entries [0]}}</td>
                <td><input type="number" class="is-center" id="number" value="1" style="width: 50%;" /></td>
                <td>{{entries [2]}}</td>
                <td>{{entries [3]}}</td>
              </tr>
            </tbody>

I tested the code above with the values in arr as shown below:

arr = [['a','b','c','d'],['a1','b1','c1','d1']]

The output I obtained was:

Answer №3

You don't need to loop through itemArrays. Simply access the elements using the index.

Get rid of the *ngFor on each row containing itemArrays.

<tbody>

              <tr *ngFor="let itemArrays of arr">
                <td>{{itemArrays[1]}}</td>
                <td >{{itemArrays[0]}}</td>
                <td><input type="number" class="is-center" id="number" value="1" style="width: 50%;" /></td>
                <td >{{itemArrays[2]}}</td>
                <td>{{itemArrays[3]}}</td>

              </tr>

            </tbody>

Answer №4

When working with the td element, you can directly access the array items without the need for *ngFor directive.


            <tbody>
              <tr *ngFor="let itemArrays of arr">
                <td>{{itemArrays[1]}}</td>
                <td>{{itemArrays[0]}}</td>
                <td><input type="number" class="is-center" id="number" value="1" style="width: 50%;" /></td>
                <td>{{itemArrays[2]}}</td>
                <td>{{itemArrays[3]}}</td>
              </tr>
            </tbody>

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

The object may be 'null', and the argument of type 'null' cannot be passed as a parameter of type 'CloudProduct' in Angular

After successfully creating my backend API with functionalities to create, update, and delete products, I have been tasked with developing the frontend using Angular and Bootstrap. While I managed to make the homepage visually appealing, I encountered issu ...

Tips on invoking Bootstrap's collapse function without using JQuery

We are facing a challenge with our TypeScript files as we have no access to jQuery from them. Our goal is to trigger Bootstrap's collapse method... $(object).collapse(method) but without relying on jQuery. Intended Outcome //Replicates the functio ...

Is it possible to create models that can be used in both Node.js and angular without duplication

Currently, I am diving into the world of Node.js and Angular (part of a MEAN project) through an online course on Udemy. One challenge I have encountered is the need to create identical models for both the back-end and front-end (specifically with angular2 ...

Issue encountered while attempting to package Azure project in Visual Studio 2015 Update1 due to difficulty copying Typescript files

Since upgrading to VS 2015 Update 1 (that includes Typescript 1.7) and Azure SDK 2.8, packaging my Azure application for deployment has become a challenge due to an error in the file path where the packager is attempting to copy the js output file: Erro ...

Using numerous maps within Ionic applications with the JavaScript SDK

Currently, I am utilizing the Google Maps (Javascript SDK) in Ionic V3 and have successfully created two pages with map views. Interestingly, while the first page displays the map correctly, upon opening the second page, the map shows up with grey lines, ...

When trying to reload Angular 8 pages, encountering an error that reads "Cannot GET /login" and also receiving a notification stating the image '/favicon.ico' cannot be loaded due to a violation of

Encountering an issue with the error message "Cannot GET login/" appearing on the page body of my latest Angular 8 app. Despite attempting various solutions found on forums, I have been unable to resolve this error. Any suggestions or advice would be great ...

Is it possible to utilize instanceof to verify whether a certain variable is of a class constructor type in TypeScript?

I am currently facing an issue with a function that takes a constructor as a parameter and creates an instance based on that constructor. When attempting to check the type of the constructor, I encountered an error. Below are some snippets of code that I ...

Can classes from an external package be imported into an Angular library within an Angular app using Openlayers?

I am currently developing an Angular library that configures an OpenLayers map as an Angular component. The component is functioning properly, but I need to access classes and constants from a package imported by the library, specifically OpenLayers. To w ...

Update the options in a dropdown menu after submitting a modal form

In my scenario, I have a modal form called "AddProductComponent" which is utilized within the "AddServiceRecordsComponent". export class AddProductComponent implements OnInit { id!: string; isAddMode: boolean = false; constructor(private fb: FormBuilder, ...

Is it possible to execute the .push() method on an array a specific number of times without using a for loop?

Currently, I am tackling the "Move Zeroes" Leetcode challenge. The task requires moving all zeroes to the end of the array without altering the sequence of non-zero elements. My strategy involves iterating through the array, splicing out each zero encounte ...

prolonging inner interface created by supabase

Below is the Typescript interface that has been generated by Supabase export interface definitions { Users: { /** Format: uuid */ id: string; /** * Format: timestamp with time zone * @default now() */ created_at?: string; ...

Ways to ensure that an angular radio button is selected as the default option

I've been attempting to have an angular mat button automatically checked, but for some reason, it's not working! <div class="container shadow"> <mat-radio-group> <mat-radio-button class="mat-button-custom" [c ...

What is the most effective method for moving a selection of elements to the left or right within a 1-dimensional NumPy array?

If I have an array like this: arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] I want to be able to shift a specified range of items either to the left or right. For instance, shifting three positions to the right, starting from position 4: >>> shift(arr ...

Is it possible to modify the chosen radio button within a template-driven form by utilizing the change event of the radio button group?

Within my Angular Material application, I have implemented a radiobutton group containing two options: "Accept" and "Reject", with corresponding values as "A" and "R". When a user selects the "Reject" option, a confirmation dialog is displayed. If the user ...

How to efficiently load a compressed bundle.js file in Angular2 with Webpack?

I recently utilized the Webpack Compression plugin to shrink my bundle.js file and successfully obtained a bundle.js.gz version. However, upon launching the application, I encountered an error: Refused to execute script from 'https://example.com/js/ ...

Css for tooltips positioned to the left and right

I have recently developed a react component tooltip that is designed to appear based on the direction (top, bottom, left, right) specified in the component parameters. Interestingly, when top or bottom is selected, the tooltip functions perfectly. However, ...

Option in TypeScript to retain the '//' in the filename when removed

I'm currently attempting to implement the angular2 quick start example in my local environment. The only feasible way for me to serve the application is as a plugin within an existing application on my system. This particular application hosts a web ...

Tips on eliminating the warning that arises when adding Bootstrap to the styles.css file in Angular

After adding Bootstrap v4.1.0 to my Angular Project's styles.css, I encountered a warning in the console. [WDS] Warnings while compiling. ./src/styles.css (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.j ...

Issues with compiling arise post downloading the latest Angular 2 quickstart files

My Angular 2 project was running smoothly on version 2.3, but I decided to upgrade to version 2.4. To do so, I downloaded the latest quickstart files from https://github.com/angular/quickstart After replacing my tsconfig.json, package.json, and systemjs.c ...

What is the best way to clear all console output on Windows?

I'm currently working on a NodeJS script that needs to clear the windows console programmatically. I don't want to just slide the console output out of view, but actually erase it completely. The tool I am developing is similar to TypeScript&apo ...