Exploring the Nested JSON Data Loop with *ngFor in Angular 5/4

Recently I started working with Angular, and I've created a service to iterate over nested JSON data for my list.

export const CATEGORIES: Category[] = [
{
    id: 1,
    categoryName:'Accessories',
    subcatName: [
        {subcategory: 'belts',}
    ],
},
{
    id: 2,
    categoryName:'Clothing',
    subcatName: [
        {subcategory: 'jeans'},
    ],
},

];

Additionally,

@Injectable()
export class CategoriesService {

 constructor() { }

  getCategories(): Category[]{
    return CATEGORIES;
  }
}

I'm currently attempting to display this data in my list using the following code:

<ul>
    <li *ngFor="let cat of categoryList">
        <a href="#">{{cat.categoryName}}</a>
            <ul>
            <li *ngFor="let subcat of categoryList">
                <a href="#"> asdad {{subcat.subcategory}}</a>
            </li>
        </ul>
    </li>
</ul>

To achieve this, I've included the following code in my component .ts file:

 export class CategoriesComponent implements OnInit {

 categoryList: Category[];

 constructor(private categoryservice: CategoriesService) { }

 ngOnInit() {
   this.categoryList = this.categoryservice.getCategories();
 }

}

I seek assistance in creating a navigation bar list of categories that reveals the relevant subcategories upon hover. Please don't hesitate to ask if you require any more details.

Answer №1

make sure to iterate through the inner array within the nested loop

<ul>
    <li *ngFor="let cat of categoryList">
        <a href="#">{{cat.categoryName}}</a>
            <ul>
            <li *ngFor="let subcat of cat.subcatName">
                <a href="#"> test {{subcat.subcategory}}</a>
            </li>
        </ul>
    </li>
</ul>

Answer №2

Make sure your inner loop is iterating over the "cat" of the parent, not categoryList.

Modify

From

 <li *ngFor="let subcat of categoryList">
    <a href="#"> asdad {{subcat.subcategory}}</a>
 </li>

To

<li *ngFor="let subcat of cat.subcatName">
     <a href="#"> asdad {{subcat.subcategory}}</a>
</li>

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

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

Removing a selected row from a data table using an HTTP request in Angular 2

I am working with a table that has data retrieved from the server. I need to delete a row by selecting the checkboxes and then clicking the delete button to remove it. Here is the code snippet: ...

What are the steps to generate a customizable datatable with various columns and information?

My application allows users to select options from a dropdown menu, which triggers a request and displays the output - typically a table - on the website. The data is always in JSON format, like the examples shown below: '{"columns":["C1","C2"], "dat ...

execute the function once the filereader has completed reading the files

submitTCtoDB(updateTagForm:any){ for(let i=0;i<this.selectedFileList.length;i++){ let file=this.selectedFileList[i]; this.readFile(file, function(selectedFileList) { this.submitTC(updateTagForm,selectedFileList); }); } } } ...

Generating a highchart by retrieving JSON data using AJAX

I'm currently working on generating a basic chart on a webpage using data from a MySQL database that is fetched via a MySQL script. My main challenge lies in understanding how to combine the ajax call with the necessary data for the chart. I'm n ...

Error: This property is not available on either 'false' or 'HTMLAudioElement' types

When working with React (Next.js) using hooks and typescript, I encountered an issue while trying to create a reference to an Audio element. The error message I received was: Property 'duration' does not exist on type 'false | HTMLAudioEleme ...

How to use SASS mixins in Angular 5 components

Within my Angular 5 project, I have organized my SASS styles into a separate directory which contains all the variables, functions, and mixins. These are then imported into my main style.scss file. @import 'abstracts/variables', 'abstracts/ ...

Extending fabric.js toObject with custom properties can result in the loss of default properties

After doing extensive research on various platforms, including this one, I am still struggling to get everything working as desired. My main goal is to save custom properties in all shapes, specifically the uuid and rt_attributes. Following the manual, I ...

The web service consistently provides a combination of XML and JSON formats. Is there a way to convert it to solely

I have been assigned a project where I need to create a webservice that strictly returns JSON data. Despite my efforts, the code I've written always returns a combination of XML and JSON response. namespace DotMeTast { [WebService(Namespace = "h ...

The Laravel model's attribute appears as empty in the JSON response

In my Laravel 4.2 project, I have a model with a 'status' attribute and declared an accessor to handle it: public function getStatusAttribute($status) { if (isset($this->expires_at) && strtotime(\Carbon\Carbon::now()) > ...

Refreshing iOS UiCollectionView with a custom UiCollectionViewLayout

Currently, I am facing a small issue while attempting to implement a custom UiCollectionViewLayout into my project. The objective is to fetch JSON data from the web and display it in a UICollectionView. However, when I integrate my own layout instead of us ...

Guide to retrieving information from a server (PHP) with RPC in Android using JSON format

I am new to Android development and I am currently working on creating an RPC to retrieve data from a PHP server in JSON format. Everything seems to be set up correctly, but I'm not receiving any data in response. Below is the code snippet from my And ...

Swift 4 Decodable - working with arrays of custom objects

I'm working with an API that has a structure similar to the following: { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2bab7bebebd92b7aab3bf">[email protected]</a>", "settings": [ { ...

Enhance constructor functionality in Ionic 4 by incorporating additional parameters

Recently, I started using Ionic and came across a location page. In the location/location.page.ts file, there was an automatically generated empty constructor like this: constructor() { } Initially, the page functioned properly with this setup. However, ...

the process of extracting data from a request body in Angular 2

After creating a URL for end-users to access, I wanted to retrieve data from the request body when they hit the URL from another module. The process involves fetching the data from the request body, passing it to my service, and then validating the respons ...

Define the width of jqgrid

I have been utilizing SmartAdmin jqgrid to showcase data in tabular format. The number of columns in the datatable changes dynamically each time. I am converting the DataTable to a JSON object and assigning it to the jqgrid. However, it appears that jqgrid ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...

Ways to resolve the Ionic v1 deprecation error problem

I am facing a problem with an Ionic v1 deprecation error, causing it to not work properly. ionic build ios ionic emulate android The basic commands are failing to produce the desired outcome. Is there a way to resolve this issue? Note: My application is ...