A guide to utilizing ngFor in Angular 7 to loop through nested JSON and display it in a ul li

Looking to insert a nested JSON into an unordered list using ngFor loop in Angular. Here's the expected output format in HTML:

home.component.html

<div class="col-md-3" id="leftNavBar">
  <ul *ngFor="let item of nestedjson">
    <li class="parentNav">{{item.name}}</li>
    <li class="childData">
      <ul>
        <li *ngFor="let subItem of item.value">{{subItem}}<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
</div>

home.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit { 

    nestedjson:any;
 constructor(private formBuilder: FormBuilder) {


     }

  ngOnInit() {
      this.nestedjson = [{"name":"parent1","value":["child11","child12"]},{"name":"parent2","value":["child2"]},{"name":"parent3","value":["child3"]}];

} 




}

Answer №1

Here is a revised version:

Live Demo

<div class="col-md-3" id="leftNavBar">
  <ul *ngFor="let item of nestedjson">
    <li class="parentNav">parent1</li>
    <li class="childData">
      <ul>
        <li *ngFor="let child of item.value">{{child}}<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
</div>

Answer №2

That's quite simple. It might be helpful to give it a shot on your own first.

https://i.sstatic.net/kYSDs.png

<div class="col-md-3" id="leftNavBar">
    <ul *ngFor="let nested of nestedjson">
        <li class="parentNav">{{ nested.name }}</li>
        <li class="childData">
            <ul>
                <li *ngFor="let val of nested.value">{{ val }}<span class="pull-right"><input type="checkbox"></span></li>
            </ul>
        </li>
    </ul>
</div>

Stackblitz: https://stackblitz.com/edit/angular-mhtnsd

Answer №3

The solution provided can be found below. Feel free to explore it on StackBlitz. Compare your solution with ngFor side by side.

<div class="col-md-3" id="leftNavBar">
  <ul *ngFor="let parent of nestedJson">
    <li  class="parentNav">{{parent.name}}</li>
    <li class="childData">
      <ul>
        <li *ngFor="let child of parent.value" >{{child}}<span class="pull-right"><input type="checkbox"></span></li>
      </ul>
    </li>
  </ul>
</div>

In case you have a JSON string, make sure to utilize JSON.parse() in order to obtain the object arranged as shown above.

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

Error message in VueJS TypeScript: Implicit declaration of type 'props' as 'any'

Currently, I am working with vue 2.6 and typescript 3.8.3. The issue arises when I attempt to apply a validator to a prop. I am encountering error message TS7006: Parameter 'props' implicitly has an 'any' type. Below is the ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

Tips for saving data from an observable into a variable or property

I've been diligently working on a project utilizing both Angular and Firebase/Firestore. Here is the code snippet that I have implemented: this.cadet = this.cadetCollection.valueChanges().subscribe(x => { this.cadetName = x[0].Cadet; this.cad ...

What is the best method to fill a mat-select dropdown with an existing value?

I am encountering an issue with a mat-form-field that contains a dropdown of data fetched from an API. I can successfully select an option and save it to the form. However, upon returning to the dropdown or reloading the page, the saved value does not appe ...

Error encountered in typescript when trying to implement the Material UI theme.palette.type

Just starting out with Material UI and TypeScript, any tips for a newcomer like me? P.S. I'm sorry if my question formatting isn't quite right, this is my first time on Stack Overflow. https://i.stack.imgur.com/CIOEl.jpg https://i.stack.imgur.co ...

Common problems encountered post Typescript compilation

I encountered the same problem. Below is my tsconfig settings: "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "newLine": "LF", &q ...

Incorporate Angular Material into a personalized library

In my quest to create a reusable library for various projects, I decided to embark on building my own from scratch. The process began with the formation of a new application solely dedicated to housing this library: ng new lib-collection cd lib-collection ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Altering the parent component's output depending on a boolean value established in the child component within Angular

Recently I began learning Angular and find myself in need of some assistance when it comes to managing a specific situation with Angular 16. In our project, we have two different versions of the site header represented by two components - one as the defaul ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

Uploading multiple strings to an Amazon S3 bucket using Node.js by piping a string

Suppose I have a simple loop similar to the one shown below: for (const i=0; i<3; i++) { to(`This incrementer is ${i}`) } At the end of the loop, I expect my file to contain: This counter is 0 This counter is 1 This counter is 2 I at ...

Facing issue in Visual Studio 2015 with Angular 2 @component not able to resolve the signature of the class decorator

Trying to define a decorator on top of my class in Visual Studio 2015 is causing an error during the build process. The specific error message states: "Build: Unable to resolve signature of class decorator when called as an expression." import { Component ...

Angular 6 and the intricacies of nested ternary conditions

I need help with a ternary condition in an HTML template file: <div *ngFor="let $m of $layer.child; let $childIndex=index" [Latitude]="$m.latitude" [Longitude]="$m.longitude" [IconInfo]="$childIndex== 0 ? _iconInfo1:$c ...

Exploring the Differences Between ionViewWillEnter and ionViewDidEnter

When considering whether to reinitiate a cached task, the choice between ionDidLoad is clear. However, when we need to perform a task every time a view is entered, deciding between ionViewWillEnter and ionViewDidEnter can be challenging. No specific guid ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

There is a clash between the webpack-dev-server package and its subdependency, the http-proxy-middleware

Awhile back, I integrated webpack-dev-server v3.11.0 into my project, which - upon recent inspection - relies on http-proxy-middleware v0.19.1 as a dependency. Everything was running smoothly until I separately installed the http-proxy-middleware package a ...

When trying to pass 3 parameters from an Angular frontend to a C# MVC backend, I noticed that the server side was receiving null

I have encountered an issue where I am attempting to pass 3 parameters (2 types and one string) but they are showing up as null on the server side. Below is my service: const httpOptions = { headers: new HttpHeaders({ 'Content-Type&ap ...

Implementing routing for page navigation within an angular tree structure

Can someone assist me with integrating a route into an angular tree structure? Here is the HTML code snippet: <mat-tree [dataSource]="dataSource" class="tree-container" [treeControl]="treeControl"> <mat-tree-node class="btnLinks" *matTreeN ...

"Encountering a 500 error on Chrome and Internet Explorer while trying to sign

I am currently working on an ASP.NET Core application that handles identity management through Azure AD B2C using the ASP.Net Core OpenID Connect. The front end is developed using AngularJS 2 with TypeScript. In my Logout function, the user is redirected t ...

Design a unique login portal separate from all other website pages

I'm a beginner with Angular and I'm currently working on creating a login page. My issue is that I want the login page to be the only component displayed initially, and once the response is 200, I want to redirect to another component. Here&apos ...