"NgFor can only bind to Array objects - troubleshoot and resolve this error

Recently, I've encountered a perplexing error that has left me stumped. Can anyone offer guidance on how to resolve this issue?

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

The JSON Array

[{

    "studentname": "ddd",
    "age": 10,
    "school": {
        "s_name": "abc school",
        "school_city": "nsw"
    }
}]

<div   *ngFor="let stu of this.studentSelected; let i = index;" >
   <tr > <td>{{stu.studentname}} :</td>
         <ng-container *ngFor="let sof stu .school">
              <td>{{s.school_city}}</td>
          </ng-container>
   </tr>
</div>

Although the error message specifies that NgFor only works with Arrays, I'm struggling to see how to fix this code.

Answer №1

If you want to solve your issue, consider converting school into an array.

It seems that in your code, you are using ngFor on stu.school, which is not actually an array. You can fix this by modifying the following line:

studentSelected = [{
    "studentname": "ddd",
    "age": 10,
    "schools": [
      {
        "s_name": "abc school",
        "school_city": "nsw"
      }
    ]
}];

By making this change, your code should run without any errors:

<div *ngFor="let stu of studentSelected; let i=index;">
   <tr>
     <td>{{stu.studentname}} :</td>
         <ng-container *ngFor="let s of stu.schools">
              <td>{{s.school_city}}</td>
         </ng-container>
   </tr>
</div>

Here is a functional example:
https://stackblitz.com/edit/angular-ivy-ikeuky?file=src/app/app.component.ts

Please take a look and let me know if it resolves your issue :-)

Answer №2

When looking at the information provided, it becomes clear that the school is categorized as an object rather than an array. This means there is no need to iterate over it in a loop. You can simply utilize it directly like so:

<div *ngFor="let stu of this.studentSelected; let i = index;">
  <tr>
    <td>{{stu.studentname}} :</td>
    <td>{{stu.school['school_city']}}</td>
  </tr>
</div>

To demonstrate and confirm this approach, I've crafted a StackBlitz example. It has been tested and proven effective. Please review for validation.

If by chance the school data is presented as an array structure, using ngFor will prevent encountering the aforementioned issues.

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

Chrome has some issues with resizing the SVG Pattern element

Utilizing inline svgs, I have a svg circle filled with a pattern that should cover 100% of the container size. However, when the parent element is resized via JavaScript, the pattern no longer reflects the 100% width and height as expected. This issue seem ...

Choose the heading element based on its class

I am trying to target a specific element by its class and store it in a variable, but I specifically need this element to be a heading element. To clarify: at any given time, there are always exactly 3 elements with this particular class on my page: an < ...

Modifying the content inside a div element and inserting an image into it

I am facing a problem where I am unable to display the image when trying to change the inner HTML of a div by inserting an img source into it. Below is my JavaScript code snippet: var sliderimg = document.getElementById('abc_'+obj).src; $("#eve ...

Vue: Ensuring one method finishes executing before triggering the next one

I've implemented two methods in my Vue instance; const app = new Vue({ el: '#app', data: { id: null }, methods: { getId: function() { return axios.get('url') .then(response => response.data) .then(i ...

Insert a numerical value into a list to make a series of numbers whole

I currently have an array of objects that looks like this: var arr = [ { "code": "10", }, { "code": "14", } ] My goal is to expand this array to contain 5 elements. The numbers should ran ...

Choose a phrase that commences with the term "javascript"

I need assistance in creating two unique regular expressions for the following purposes: To select lines that begin with 'religion'. Unfortunately, my attempt with /^religion/g did not yield any results. To match dates and their correspondi ...

Guide on using react-highlight-words to emphasize various keywords using different color schemes

I am currently working on implementing a search feature for my React project. At the moment, I am only required to enter a single keyword and search for it within the text. Once found, I need to extract and display the sentences containing this keyword sep ...

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

When running npx webpack, an error occurred stating, "Property 'minify' cannot be read from undefined."

I've been following the introductory tutorial on webpack from this particular link: https://webpack.js.org/guides/getting-started/ However, when I attempt to execute npx webpack, it encounters an error as shown below: ERROR in main.js from Terser Ty ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...

Sending a JavaScript function as part of an ajax response

I'm currently working on a system where the user can submit a form through AJAX and receive a callback in response. The process involves the server processing the form data and returning both an error message and a JavaScript function that can perform ...

ReactJs: Tweaking Padding in Material-UI Table

After inheriting this fullstack app, I noticed that the original developers had incorporated a component to generate tables for the webpage. However, there is an issue with the padding on all the cells being too large. Through Chrome developer tools, I di ...

Navigating a path and executing unique functions based on varying URLs: A guide

I am trying to send a post request to the path /users and then right away send another post request to /users/:id. However, I need the actions to be different for each of these URLs, so I cannot use the array method to apply the same middleware. The goal ...

Template for typed variable - `ng-template`

How can the parent component correctly identify the type of let-content that is coming from ngTemplateOutletContext? The current usage of {{content.type}} works as expected, but my IDE is showing: unresolved variable type Is there a way to specify the ...

Analyzing two arrays and utilizing ng-style to highlight matching entries within the arrays

My list displays words queried from a database, allowing me to click on a word to add it to another list that I can save. This functionality enables me to create multiple word lists. My goal is to visually distinguish the words in my query list that have a ...

jQuery AJAX Triggered Only Once in Callback Function

I am facing an issue with the jQuery get function within my updateMyApps. The function works fine when called directly after it is declared. It successfully loops through the data and appends elements to the DOM. However, when I submit the form #addapplic ...

Creating a OneToMany relationship in NestJS entity model

In my current project with NestJS, I am working on defining entity fields. While I have successfully defined a ManyToOne relation, I am facing difficulties in setting up the syntax for a OneToMany relation to match the structure of my other relationships. ...

Passing a method as a parameter type

As I delve into learning JavaScript from Objective-C, I find myself pondering whether it is possible to have a method with parameter types in Objective-C. Let's take the example of the findIndex() JavaScript function that identifies and returns the in ...

Transform a section of text into JSON format to utilize in DataTables

Currently, I am utilizing DataTables and Leaflet in my project. The data displayed below needs to be represented on my screen using Datatables. Specifically, I would like to convert it into JSON format without including the {....} part. How should I proc ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...