A comprehensive guide on utilizing the ngFor directive for looping through objects

After trying to iterate over this dataset within my HTML, I attempted a nested ngfor, but unfortunately encountered an error.

My attempt involved iterating the object twice with a nested ngfor, resulting in the following error:

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

Below is the data object in question:

{
  "Sat Jan 05 2019": [
    {
      "completed1": true,
      "frequency": [
        7,
        6,
        2,
        1
      ],
      "description": "Walk 100km",
      "color": "#E97825",
      "task_id": "00397030-182d-11e9-957b-79c872c75fe1"
    },
    // More data entries here...
  ]

Displayed below is the snippet from my HTML code:

<div class="records-calendar">
    <div class="records-container" *ngFor="let formattedHabit of formattedHabits"></div>
    <div class="" *ngFor="let habit of formattedHabit"></div>
</div>

And here is the relevant TypeScript component code:

import { Component, OnInit, Input, } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import * as moment from 'moment';

// Rest of the TypeScript code here...

Answer №1

To properly implement your component, the code must include a public variable called 'formattedHabits' that is an array of objects reflecting the data structure mentioned.

If you wish to utilize the JSON format provided in your question, consider creating a public variable 'formattedHabits' of type 'any' and use JSON.parse to convert the JSON object into a JavaScript object.

const formattedHabits: any = JSON.parse('your json');

Regarding the nested loop, ensure that the divs are nested accordingly as well.

<div class="records-container" *ngFor="let formattedHabit of formattedHabits">
    <div class="" *ngFor="let habit of formattedHabit.habits">{{habit.description}}</div>
</div>

The loop in your example will not work since you are attempting to iterate through an object that is not a collection.

Refer to my code snippet, which demonstrates a proper nested loop to display the description of each individual habit.

Furthermore, leverage TypeScript by specifying the actual types of variables instead of using 'any' for better utilization of its capabilities.

Answer №2

ngFor can only iterate over 'iterables', formattedHabits is not currently iterable. To make it iterable, you could transform it into an array like the following example:

{ "dateHabits": [   
    {
      "date": "Sat Jan 05 2019",
      "habits": [
        {
          "completed": true,
          "frequency": [
            7,
            6,
            2,
            1
          ],
          "description": "Walk 100km",
          "color": "#E97825",
          "task_id": "00397030-182d-11e9-957b-79c872c75fe1"
        }
      ]
    }
  ]
}

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

Determining the current element's index as I scroll - using Jquery

If I have a series of divs with the class name 'class' that are fixed height and enable auto-scrolling, how can I determine the index of the current 'class' div I am scrolling in? Here is an example: var currentIndex = -1; $(window).sc ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

Encountering numerous errors while attempting to upgrade from Angular 9 to Angular 11

On Thursday of last week, I initiated an Angular update and unfortunately, I have been encountering numerous errors ever since. The most recent error while running ng serve -o is: An unhandled exception occurred: ENOENT: no such file or directory, lstat &a ...

what's the reason for ajax constantly sending requests back-to-back?

Today, I find myself pondering. In my current project, the ajax calls are not behaving asynchronously. Each request is being sent one after the other. As one request is being processed, all other requests are getting stuck in a pending state. You can ob ...

Webpack fails to handle CSS background images

I'm having trouble with my Webpack configuration as it's not processing CSS images set in the background property: background: url('./hero.jpg') no-repeat right; This is resulting in an error message that reads: ERROR in ./src/app/comp ...

Encountering a 405 Error while attempting to perform a search on Twitter

I have been attempting to search Twitter using jQuery, but I am encountering an issue. The response only shows: https://api.twitter.com/1.1/search/tweets.json?q=django 405 (Method Not Allowed) XMLHttpRequest cannot load https://api.twitter.com/1.1/search/ ...

What is the reason for the directive being available in $rootScope?

Currently, there doesn't seem to be a major issue but it has sparked my curiosity. I have a straightforward directive that, for some unknown reason, is accessible within $rootScope. JAVASCRIPT: (function(){ var app = angular.module('myAp ...

Refresh Form Following Submission

When using a react form that triggers a graphql mutation upon button click, the text entered in the form fields remains even after the mutation has been executed. This necessitates manual deletion of text for subsequent mutations to be run. Is there a way ...

Upgrade from AngularJS to Angular 5 in Eclipse

Currently, I have a web application built in AngularJS, but I am looking to transition it to Angular 5. The existing webapp is running on Eclipse with a Tomcat server and has Java as the backend language. I have created a new version of the web applicati ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below: // base.js module.exports = function BaseClass () { // ... ... }; M ...

Angular: Identifier for Dropdown with Multiple Selection

I have recently set up a multi select dropdown with checkboxes by following the instructions provided in this post: https://github.com/NileshPatel17/ng-multiselect-dropdown This is how I implemented it: <div (mouseleave)="showDropDown = false" [class. ...

stop automatic resizing of windows

My CSS is written using percentages. I need to maintain the percentages intact. Is there a way to stop the layout from changing when the browser window is resized? I want the percentages to remain unaffected, even when the browser window is being resized ...

Using local variables in Angular2 templates

For the specific scenario discussed below, I have assigned the local variable #input to multiple radio buttons. My goal is to select the radio button within the <tr> when it is clicked. Surprisingly, the provided code functions as expected, yet the ...

The server encountered an error: TypeError - It is not possible to convert undefined or null into an

Check out this Code import { getProviders, signIn as SignIntoProvider } from "next-auth/react" function handleSignIn({ providers }) { return ( <> {Object.values(providers).map((provider) => ( < ...

Check if the content key Json exists by implementing Vue

Can anyone help me with checking the existence of "novalue"? For instance: { name: "maria", city_id: "novalue" .... } What would be the best way to do this in Vue? Should I use <div v-if="condition"> or a function? ...

Explanation for the strange floating math in JavaScript - Understanding the IEEE 754 standard for laymen

When it comes to JavaScript and working with floating point numbers, I always feel a bit lost. Dealing with decimals makes me nervous because I'm never quite sure what's happening behind the scenes. If only I understood how the IEEE 754 standard ...

Testing an Angular service call

I am currently testing whether a button click will trigger a method call in the service. Here is an excerpt of the component content: ngOnInit() { try { //GET ALL ITEMS this.service.getAll().pipe(untilDestroyed(this)).subscribe((result) =& ...

Managing multiple asynchronous requests through Observables in web development

I am working on an Angular2 website that sends multiple ajax requests using Json Web Tokens for authorization when it is initialized Here are two examples: public getUser(): Observable<User> { // Code block to get user data } public getFriends ...

React: Updating a state before calling another function - Best practices

In my code, there is a state variable named list that gets updated whenever the function setList is called. The setting of the list happens within the function AddToList, where a new value is added to the existing values in the list. However, I have notice ...