Exploring the method of iterating through nested arrays in Angular

I have a nested array structured like this:

tests: [
  [{name:"Bob",score:40,subject:"Math"}, {name:"John",score:55,subject:"Math"}],
  [{name:"Alice",score:70,subject:"English"},{name:"John",score:68,subject:"English"}]
],
// ...

My goal is to loop through the array and print the data while grouping students by subjects. Here's my attempt:

<div *ngFor = "let test of tests;let i = index">
  <ul *ngFor = "let student of test[i] ;let n = index">
     <li>{{student.name+' '+student.score}}</li>
  </ul>
</div>

However, I encounter an error that says:

ERROR Error: Cannot find a differ supporting object [object Object] of type 'object'. NgFor only supports binding to Iterables such as Arrays.

This error occurs during the second loop. Can anyone help me understand what I'm missing here?

Answer №1

Recently modified the code by changing test[i] to test, which is now an array that can be iterated. Previously, test[i] was an object and could not be iterated.

Here is the TypeScript code snippet:

 tests = [
          [{name:"Bob",score:40,subject:"Math"},{name:"John",score:55,subject:"Math"}],
          [{name:"Alice",score:70,subject:"English"},{name:"John",score:68,subject:"English"}]
        ]

And here is the corresponding HTML code snippet:

<div *ngFor = "let test of tests; let i = index">
    <ul *ngFor = "let student of test ; let n = index">
        <li>{{student.name+' '+student.score}}</li>
    </ul>
</div>

Check out the live demo here.

Answer №2

Here's how you can iterate through the given array:

<div *ngFor="let item of items">
  <ul *ngFor="let value of item">
     <li>{{value.name+' '+value.score}}</li>
  </ul>
</div>

Answer №3

While I may not be an expert in Angular development, here is a suggestion:

Instead of using let student of test[i], consider changing it to let student of tests[i] or simply let student of test

Answer №4

Give this a shot!

 let exams = [
              [{name:"Bob",score:40,subject:"Math"},{name:"John",score:55,subject:"Math"}],
              [{name:"Alice",score:70,subject:"English"},{name:"John",score:68,subject:"English"}]
            ];

<div *ngFor="let exam of exams">
    <ul *ngFor="let student of exam">
       <li>{{student.name+' '+student.score}}</li>
    </ul>
  </div>

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

When setting up a list in TypeScript, it does not verify the type of each element during initialization

In TypeScript, the code snippet below does not generate any error or warning, even though the 1st element does not adhere to the IFileStatus interface: interface IFileStatus { a: string; b: number; } let statuses: IFileStatus[] = [ { ...

Sending reference variable from Angular input type=file

I am currently learning Angular and I have implemented a feature where a list of PDF files is displayed using an array called pdfs. In my template, these PDF files are parsed into "card" elements for better visualization. The issue arises when I attempt ...

The positioning of the Zorro table column remains flexible despite the presence of nzLeft

I am currently developing a project using Angular. Within one of my components, I have a table that displays some data. This table is generated by the ng-zorro table module. However, I've encountered an issue where setting a table column or header wi ...

Exploring the capabilities of observables in mapping nested dynamic object keys, specifically focusing on manipulating data within angular-calendar events

Perhaps utilizing something like map<T,R> would be a better approach than my current method. I am hoping to receive some advice on how to resolve this issue. Currently, no events are being mapped due to incorrect mapping resulting in an incorrect pat ...

The Angular Library seems to be malfunctioning as it does not execute the ngOnInit

I've been following the instructions from Angular CLI 6 to create a library, which can be found here. So far, I've successfully created and built my library. It includes a Component that I'm using for the UI and has an HTML selector. @Compo ...

Encountering an issue with NgRx store where the property 'products' is not recognized on the type 'ActionCreatorProps<{ payload: Product[]; }>' while attempting to build a reducer

Currently, I am delving into the @ngRx/store package within my Angular 14 App. My primary goal is to establish a basic store capable of containing a simple object Array. Here is an excerpt from my action file: import { Product } from 'src/app/data-mod ...

Sending emails with Angular 9: A step-by-step guide

Here is a code snippet that demonstrates how to send an email from the server side. I am looking for guidance on how to integrate this code into an Angular 9 application. Any assistance would be greatly appreciated. var nodemailer = require('node ...

What are some ways to customize formControlNames in Angular reactive forms?

Is there a way to customize the formControlName in Angular forms? I need to be able to toggle check-boxes on and off based on certain values within a nested object array. Here is an example of what the HTML code might look like: <span class="col-md-2" ...

How can I use Angular 4 typescript to deactivate a button based on the value of a boolean variable?

I am looking to define a function in TypeScript called 'isActive()', which I will then invoke on a button within my HTML file. Additionally, I have already declared a boolean variable named 'isActive'. In this scenario, I have two butto ...

What events can cause all store states to be loaded when the page is altered?

I am currently utilizing ngrx/store, ngrx/effects, and ngrx/router. The implementation of my effects is structured as follows: @Effect() loadOneProduct$ = this.updates$ .whenAction(LOAD_ONE_PRODUCT) .switchMap(() => this.productService.loadOn ...

Adjust the column width dynamically in an Ionic framework

Need help with changing the size of a Column element dynamically. <ion-col [size]="this.size" [size-xl]="this.size_xl" [size-md]="this.size_md" [size-sm]="this.size_sm" [size-xs]="this.size_xs"> Faci ...

The Angular 2 HTTP GET method is throwing a type 3 error when trying to access the

i am encountering an issue while trying to retrieve a response from my asp.core api within Angular 2. The error message received is: "Object { _body: error, status: 0, ok: false, statusText: "", headers: {…}, type: 3, url: null }" Component: import { C ...

I'm looking for a way to merge the functionalities of tsc build watch and nodemon into a single Node.js

Currently, I have two scripts in my code: "scripts": { "build": "tsc -p . -w", "watchjs": "nodemon dist/index.js" } I need to run these two scripts simultaneously with one command so that the build ...

Development of backend applications using Node.js and Express, coupled with frontend interfaces built with Angular

I created a web application, utilizing Node.js with Express and MySQL for the backend, and Angular framework for the frontend. Check here While everything works smoothly in my local environment (using Mamp and port 3000 for testing), I am encountering dif ...

What's the best way to invoke this specific TypeScript function?

I have come across a library that includes the following function declaration: import { Auth0JwtStrategy } from './strategy/auth0-jwt.strategy'; import { Auth0Service } from './auth0.service'; import { Auth0Options } from './auth0. ...

Can we incorporate 'this' in the super() constructor?

While reviewing someone else's code, I came across the following snippet: class foo extends bar { constructor() { super(param1, param2, new certainObject(this, otherParams)); } } The issue with this code is that it generates an error ...

Leveraging Typescript Generics for limiting the input parameter of a function

Issue I have developed a Typescript package to share types between my backend node firebase cloud functions and frontend React client that accesses them. Provided below are examples of the types: interface FirstFunctionInput { x: number } interface Sec ...

Implementing noData functionality in highcharts using angular

I want to activate the "noData" feature, which shows a message when there is no data for the chart. According to the documentation, this feature requires loading the file no-data-to-display.js on the page. The file is already in the node_modules/highchart ...

What could be causing TypeScript to forego type inference and default to 'any' in this scenario?

While refactoring parts of our React app in TypeScript, I encountered a challenge that required me to use what I consider to be a less than ideal double type argument. I'm unsure if this is a bug in TypeScript or if there is some type ambiguity causin ...

What causes items within an Array() to be interdependent? (Javascript)

Here is what I attempted: let array = Array(2).fill([]); array[0].push(1); Expected result: array = [[1], []] Actual result: array = [[1], [1]] Can someone explain why the second element is affected by the first in this scenario? Appreciate any help in ...