Exploring Angular's nested categories with the power of *ngFor loop

I am facing a challenge with an undefined number of arrays that can be nested without limit. This is for the "filtering" section on a page where products are listed. However, I am struggling to dynamically create this structure on the HTML side.

[
    {
      "name": "Models",
      "items": [
        {
          "name": "Fabric",
          "fieldType": "checkbox",
          "subCategories": []
        },
        {
          "name": "Linen",
          "fieldType": "checkbox",
          "subCategories": [
            {
              "name": "Colored",
              "fieldType": "checkbox",
              "subCategories": []
            },
            {
              "name": "Solid Color",
              "fieldType": "checkbox",
              "subCategories": [
                {
                  "name": "Black",
                  "fieldType": "checkbox",
                  "subCategories": []
                },
                {
                  "name": "White",
                  "fieldType": "checkbox",
                  "subCategories": []
                },
                {
                  "name": "Red",
                  "fieldType": "checkbox",
                  "subCategories": []
                }
              ]
            }
          ]
        }
      ]
    },
    {
      "name": "Other",
      "items": [
        {
          "name": "Radio Buttons",
          "fieldType": "checkbox",
          "subCategories": [
            {
              "name": "Radio 01",
              "fieldType": "radio",
              "subCategories": []
            },
            {
              "name": "Radio 02",
              "fieldType": "radio",
              "subCategories": []
            }
          ]
        }
      ]
    }
  ]

Looking at the "HTML" implementation, here's the code snippet.

  <div class="filter-item">
    <span class="filter-item-title">Models</span>
    <ul>
      <li>
        <mat-checkbox color="primary">Fabric</mat-checkbox>
      </li>
      <li>
        <mat-checkbox color="primary">Linen</mat-checkbox>
        <ul>
          <li><mat-checkbox color="primary">Colored</mat-checkbox></li>
          <li>
            <mat-checkbox color="primary">Solid Color</mat-checkbox>
            <ul>
              <li><mat-checkbox color="primary">Black</mat-checkbox></li>
              <li><mat-checkbox color="primary">White</mat-checkbox></li>
              <li><mat-checkbox color="primary">Red</mat-checkbox></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
  <div class="filter-item">
    <span class="filter-item-title">Other</span>
    <ul>
      <li>
        <mat-checkbox color="primary">Radio Buttons</mat-checkbox>
        <ul>
          <li>
            <mat-radio-group aria-label="Select an option">
              <mat-radio-button color="primary" value="1">Radio 01</mat-radio-button>
              <mat-radio-button color="primary" value="2">Radio 02</mat-radio-button>
            </mat-radio-group>
          </li>
        </ul>
      </li>
    </ul>
  </div>

Check out my live sample: https://stackblitz.com/edit/angular-yzdxca. Any insights you can offer would be greatly appreciated. Thank you.

Answer №1

I'm just sharing a concept here, so feel free to customize it as needed.

This type of component is known as recursive and operates based on conditions.

recursive.component.html

<div>
  Add your content here
</div>
<!-- recursion begins -->
<app-recursive [data]="data" *ngIf="data"></app-recursive>

By allowing the component to call itself, it will repeat until there is no data available. You can control this behavior by setting a condition that stops displaying it when the data is empty.

It's important to be cautious with recursive components as they can be resource-intensive. Make sure to optimize your data management to avoid potential application crashes.

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

Steps to isolate the "changed" values from two JSON objects

Here is a unique question that involves comparing JSON structures and extracting the differences. A JqTree has been created, where when the user changes its tree structure, both the "old" JSON and "new" JSON structures need to be compared. Only the values ...

Is Cookie-session the most ideal choice for React applications?

My NodeJS application currently authenticates users through a third-party app. Once the app retrieves user data, a cookie is generated and sent to the client for React to access the user data from that Cookie. Should I stick with using cookies or consi ...

Having trouble iterating over an array in Angular's TypeScript

I've been attempting to loop through an array of objects in TypeScript, but encountered the following error: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined TypeError: Cannot read property 'fo ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Struggling to figure out how to make Bootstrap toast close or autohide properly

Looking to integrate Bootstrap 5 toasts into my ASP.NET web application, I have the code below. HTML <div class="row"> <div class="toast" id="companyUpdOK" name="compa ...

If a value is located, select a new value from the identical object

Is it achievable to scan through an array of JSON objects? My goal is to locate a particular value within one of the objects and then extract other values from that same object. Is this possible? Appreciate any guidance. Thank you. ...

Trouble with accessing Dynamic StyleSheet properties based on type restrictions

I have successfully developed a functional component in React Native that supports both light and dark theme styles. const lightThemeOverrides = StyleSheet.create({ <light_override_styles_here> }); const styles = StyleSheet.create({ <styles_here&g ...

JavaScript utilizing a PHP variable

In my attempt to merge a PHP variable with JavaScript, I aim to access the "the_link_to_the_page_I_want". window.onload = function openWindow() { window.open('the_link_to_the_page_I_want', 'newwindow', config='height ...

VS Code using Vue is displaying an error message stating: The property '' does not exist on type '{}'.ts(2339)

While working in Visual Studio Code, I came across the following code snippet: <script lang="ts" setup> const parseCSV = () => { // Code omitted for brevity } } </script> <template> <button @click="parseCSV ...

Leveraging data from a JSON array

After successfully retrieving a JSON array from PHP using AJAX, I am now faced with the task of utilizing specific values within the array. Although I can currently display the results as a string, my goal is to access and use individual values independen ...

IntelliSense for TypeScript Variable Names in Intellij

When declaring a variable or field in Java, it is common practice to specify the type. For example: public SomeDataType someDataType = new SomeDataType(123) As you begin typing Som.., IntelliJ's autocomplete feature will likely suggest SomeDataTyp ...

Exploring Angular 2's Observable Patterns and Subscribing Techniques

Despite perusing various posts and documentation on the topic, I am still unable to grasp the concept of observables and subscribing to them. My struggle lies in updating an array in one component and displaying it in another component that is not direct ...

Manipulating Hyperlinks outside the Angular JS applicationIn certain cases, Angular JS

This is my first attempt at creating a single page app. The app's content is contained within the page like a widget, functioning similar to pagination. In the header, I have links that are not related to the angular app. The link structure looks lik ...

The initialization of Firebase is not being completed before it is being called in other files

I am currently working on a vue project and I am attempting to integrate firebase. However, I have encountered an issue where my other JavaScript files like auth.js are utilizing firebase before it is properly initialized in my main.js file (which acts as ...

Is there a way to prevent Intellij from constantly compiling TypeScript at a very slow pace?

In the process of transitioning my Angular 1.x project from vanilla JS to TypeScript, I'm encountering frustratingly slow response times from my IDE.https://i.sstatic.net/LkiDj.png When I uncheck "Track changes" in Settings > Languages & Framework ...

Singleton Pattern in Angular Dependency Injection

In my code, I have a service called MyService that is decorated with the following: @Injectable({ providedIn: 'root' }) Part of its implementation includes: private myData: string = ''; setData(data: string) { this.myData = d ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

Conceal the option to "show more" when there are no additional posts to display

Is there a way to dynamically hide the load button when no more posts are available? I've included my code below: function.php function load_more_posts_ajax(){ $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: tex ...

Ways to loop through HTML elements based on certain criteria?

Issue : The v-for loop is successfully iterating and binding data in the HTML template, but there is a challenge in partially iterating it based on certain conditions. Please refer to the JSFiddle link below for a demo. Objective : In the provided demo li ...

Issue with image not loading on Next [email protected] while utilizing Image component from next/image along with tailwindcss class

I am trying to make my image responsive on mobile view. I have used tailwindcss classes to set the Image className, and it works fine when I only use reactjs or a regular img tag. I am attempting to make this image responsive. I have tried setting the layo ...