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 act() in React/Jest/MSW causes errors when waiting for a response

As I delve into learning how to unit test with React, my focus has shifted towards using TypeScript. Unfortunately, the course I am taking does not cover most errors related to TypeScript. In my testing journey, I have set up a simple testing function with ...

Encountering an error in Angular 4: 'Cannot find property on specified component type'

I recently embarked on the journey of learning Angular 4 and TypeScript, but I've encountered my first obstacle. My current challenge involves creating a simple date and time component. Despite having a seemingly correct Javascript code, I believe I ...

JSON parsing a string with leading zeros causes errors in the process

Can anyone explain why JSON.parse doesn't work when I include leading zeros in the string "000634", but works fine when the zeros are removed? I'd appreciate any insights on this. Thanks! Example where it doesn't work: var str = ' ...

Following an update from typescript version 2.3.4 to 2.4.2, I encountered a compilation error stating, "The type definition file for 'reflect-metadata' cannot be found."

Recently, I encountered an issue with my React / Mobex application written in TypeScript and built by Webpack 1. Upon updating the TypeScript version from 2.3.4 to 2.4.2, an error started occurring. The error message reads: ERROR in C:\myproject&bsol ...

Is there a way to display the text that has been selected?

I would like to display the text of a clicked link in an empty div element. Can someone help me achieve this? Thank you. <div></div> <span>link one</span> <span>link two</span> <span>link three</span> ...

Tips for using lodash to concatenate a string to an element in an array

My json object is structured like this: "data": [{ "firstName": "XYZ", "lastName": "Admin", "userId": 1, "companyLogo":"Logo" }, { "firstName": "ABC", "lastName": "Admin", "userId": 1, "companyLogo":"Logo1" }, { ...

Exploring the functionality of multiple checkboxes in Next.js 14, the zod library, shadcn/ui components, and react-hook

I'm currently working on a form for a client where one of the questions requires the user to select checkboxes (or multiple checkboxes). I'm still learning about zod's schema so I'm facing some challenges in implementing this feature. I ...

Leveraging animations in Angular2 that are defined outside of a component

I've recently put together a basic component @Component({ selector: 'saved-overlay', templateUrl: './saved-overlay.html', exportAs: 'saved-overlay', animations: [ trigger('inOut', [ transition ...

Obtaining the dimensions of each individual child component within an NgTemplate

I have the following code snippet within my template. While I can iterate through its components using `get`, it does not return an object that allows me to access deeper into the HTML attributes. <ng-template #container></ng-template> Compon ...

Integrating one service into another allows for seamless access to the imported service's properties and methods within an Angular

After reviewing the content at https://angular.io/guide/dependency-injection-in-action, it appears that what I am trying to achieve should be feasible. However, I encounter this error when attempting to invoke a method on my injected service from another s ...

Receiving data from a service in Angular 2 with rxjs subscribe throws an error: it is not a

I've recently started working with Angular and I'm encountering an issue when trying to pass the _newArray to my child component using a shared service. Service fetchData(): Observable < any > { return forkJoin(this.fetchQuestions(), th ...

Specialized serializer and deserializer utilizing GSON for a collection of BasicNameValuePairs

Struggling to create a custom Gson serializer and deserializer for a list of BasicNameValuePair objects. Found some helpful code snippets for serialization here. Decided to tackle deserialization as well, so here's my attempt: package dto; import ...

Is there a way to customize the JSON-wrapped key for a class without being able to annotate the class with @JsonTypeInfo?

I have the following code snippet: import org.codehaus.jackson.map.*; public class MyPojo { int id; public int getId() { return this.id; } public void setId(int id) { this.id = id; } public static void main(String[] args) throws ...

Why does Material-UI's "withStyles()" not function properly with a specified constructor in Typescript?

Update: Please note that there was an issue with the constructor generated by IntelliJ IDEA, but it has been fixed. You can find more details here: I'm exploring the use of Material-UI in my application, and I've encountered some challenges wit ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...

Retrieve content from Wordpress blog including image preview

Can someone help me find a PHP script that can import posts from my WordPress blog and display them on another website, complete with a thumbnail of each blog post? Thank you in advance for your assistance! ...

Steps to resolve the issue with an unexpected token in JSON: JSON::ParserError

After utilizing Vagrant for about a month, I encountered an unexpected issue yesterday when running "vagrant up" caused my computer to shut down. View image description here ...

JSON loading error detected in the system's background operation

I created a JSON loader class to load JSON objects from a URL. However, when I run it, I encounter some system errors in the logcat. Surprisingly, the application does not force close despite these errors. I am unsure about where I went wrong. Additionally ...

Skipping a JSON field in HTML/JavaScript when it is blank: A guide for developers

To develop an interactive program based on JSON input, I aim to display headers, subheaders, and choices derived from the JSON data. Some input fields may remain unfilled. For instance: Header Subheader Choice 1 Choice 2 Subheader2 Choice ...

Creating a JSON formatting structure with three layers of nesting

My goal is to create a jQuery script that will automatically populate a select box with a name and an ID based on the user's selection from another select box. However, I'm encountering difficulties in structuring my JSON file. Here are the attr ...