Using ngFor in Angular with an array consisting of nested arrays

  1. List item:
jsonObject = [
    {
      place: 'place1',
      fatherDetails: [
        {name: 'place1_father1', adharId: 134567},
        {name: 'place1_father2', adharId: 124567},
      ],
      motherDetails: [
        {name: 'place1_mother1', adharId: 123456},
        {name: 'place1_mother2', adharId: 123457},
        {name: 'place1_mother3', adharId: 123467},
      ],
    },
    {
      place: 'place2',
      fatherDetails: [
        {name: 'place2_father1', adharId: 123567},
        {name: 'place2_father2', adharId: 12567},
      ],
      motherDetails: [
        {name: 'place2_mother1', adharId: 1234567},
        {name: 'place2_mother2', adharId: 1234567},
        {name: 'place2_mother3', adharId: 1234567},
      ],
    }
  ];

I am trying to figure out how to use ngFor in HTML to loop through all the fatherDetails objects. Here's what I have attempted:

<mat-option *ngFor = "let father of jsonObject">
   {{father.name}}
</mat-option>

Unfortunately, this code isn't working as intended because it needs to iterate twice for proper looping.

Answer №1

You can easily accomplish this task by utilizing the ng-container feature in Angular.


    <ng-container *ngFor="let item of itemList>
        <mat-option *ngFor="let parent of item.parentDetails">
            {{parent.name}}
        </mat-option>
    </ng-container>

Using ng-container avoids cluttering your DOM with unnecessary elements and gives you access to nested arrays efficiently.

Answer №2

Remember to loop through the first array and then iterate the second array within each object of the first array.

jsonObject = [{
    place: 'place1',
    fatherDetails: [{
        name: 'place1_father1',
        adharId: 134567
      },
      {
        name: 'place1_father2',
        adharId: 124567
      },
    ],
    motherDetails: [{
        name: 'place1_mother1',
        adharId: 123456
      },
      {
        name: 'place1_mother2',
        adharId: 123457
      },
      {
        name: 'place1_mother3',
        adharId: 123467
      },
    ],
  },
  {
    place: 'place2',
    fatherDetails: [{
        name: 'place2_father1',
        adharId: 123567
      },
      {
        name: 'place2_father2',
        adharId: 12567
      },
    ],
    motherDetails: [{
        name: 'place2_mother1',
        adharId: 1234567
      },
      {
        name: 'place2_mother2',
        adharId: 1234567
      },
      {
        name: 'place2_mother3',
        adharId: 1234567
      },
    ],
  }
];
<tr *ngFor="let object of jsonObject; let i = index;">
  <td>{{i}}</td>
  <td * ngFor="let o of object.motherDetails">{{o}}</td>
</tr>

Answer №3

To effectively retrieve fatherDetails from each item, create a flat array and loop through it

Within the component class:

this.allfathersDetails = this.jsonObject.map(item => item.fatherDetails).flat();

In an HTML template:

<div *ngFor="let details of allfathersDetails">
 ...

Answer №4

Feel free to experiment with this piece of code.

<div *ngFor = "let item of itemList">
<div *ngFor ="let parent of item.parentDetails>
<span>{{parent.name}}</span>
</div>
</div>

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

Issue with Angular Material: Default selection not being applied in mat-select component

When I have a mat-select with options defined as objects in an array, I am facing an issue where the default selected value is not being set when the page renders. In my TypeScript file, I have: public options2 = [ {"id": 1, "name": "a"}, {"id": 2 ...

What is the reason behind the possibility of assigning the exported class to a variable within Ionic 2?

The code snippet below can be found in settings.ts: @Component({ selector: 'page-settings', templateUrl: 'settings.html' }) export class SettingsPage { } } Similarly, in the app.component.ts file, we are able to assign the Clas ...

Learn how to implement icons within Textfield components using Material-UI and TypeScript in React

I have successfully created a form with validation using TypeScript Material UI and Formik. Now, I am looking to enhance the visual appeal by adding a material UI Icon within the textfield area. Below is a snippet of my code: import React from 'reac ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

What sets apart the browser/tab close event from the refresh event?

Can you help me understand the difference between a browser/tab close event and a refresh event? I've been researching this on Stack Overflow, but I'm still having trouble with it. My goal is to be able to log out a user through a server call whe ...

Tips for resolving errors in Angular controls

Setting custom errors in Angular is straightforward with this code snippet: this.form.controls['field'].setErrors({same:true}); However, the process for removing custom errors is not as obvious. Does anyone know how to accomplish this? Are ther ...

Toggle the visibility of a modal in code across various components in an Angular 4 project using Typescript

As I was working on my university App, I encountered an issue while attempting to open a Bootstrap modal in code from a different component. Opening a component in code from the same component posed no problems for me as I use JQuery and it functions perfe ...

Loading an HTML file conditionally in an Angular 5 component

Consider a scenario in my project where I have a testDynamic component. @Component({ templateUrl: "./test-dynamic.html", // This file needs to be overriden styleUrls: ['./test-dynamic.css'] }) export class testDynamic { constructor() ...

The link path in Angular 2 seems to be eluding me

I'm having trouble accessing the page at "http://localhost:4200/values" as I keep getting this error: Error: Cannot match any routes. URL Segment: 'values' This is the structure of my code. app.routing.ts export const AppRoutes: Routes = ...

Angular - Ensuring the Independence of Field Pairs During Validation

I need to independently validate two sets of fields. One set is for passwords, which should match each other. The second set is for email addresses, which should also match. The current method I have tried isn't working. Can someone guide me on how ...

Is there a way to compile Node's global modules and objects using TypeScript while having the checkJs option enabled?

By including "checkJs": true in my tsconfig.json file, Node's global paths and objects are marked as "not found". For example, if I were to write: import path from "path"; const p = path.resolve(__dirname, 'dist/js') The TypeScript co ...

Generating a TypeScript type based on import.meta.glob's information

Currently, I am importing multiple JSON files that contain an id within their data. export type CourseInfo = { id: string; name: string; fullName: string; sku: string | null; par: string; buyCourseDescription: string | null; price: string; ...

There is an issue with the Angular 2 provider when attempting to use useValue in conjunction with a function call

I can't figure out why the syntax for Angular 2 providers isn't functioning as expected when trying to provide a specific value using the useValue field. For example, in my app.module.ts file: // Abstracted base class (since interfaces don&apos ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

What is the best way to transfer information between two components when working with an edit form?

Presently, I am utilizing a modal material dialog window that prompts the user to input a number and then press search. Upon searching, it retrieves data from an API call and receives a response object. My goal is to utilize this response object to populat ...

Angular DOM not reflecting updates

Having trouble with the view not detecting changes in value on a component. I've attempted to use ChangeDetectorRef without success. After trying various solutions and spending an excessive amount of time on something that should work smoothly, it see ...

activating serverless.yml for aws-xray

I have been attempting to implement AWS X-Ray for all lambda functions in the following manner: serverless.yml provider: tracing: lambda: true apiGateway: true name: aws runtime: nodejs8.10 stage: ${opt:stage, 'dev'} region: ...

Having trouble invoking the "done" function in JQuery following a POST request

I am currently working on a Typescript project that utilizes JQuery, specifically for uploading a form with a file using the JQuery Form Plugin. However, after the upload process, there seems to be an issue when trying to call the "done" function from JQue ...

The issue of Undefined TypeError arises when using Angular HttpInterceptor and injecting any service

Issue: I'm facing a problem where I am unable to inject any service into the constructor of my HttpInterceptors. Every service I try to inject results in the error: TypeError: Cannot set property 'authenticationService' of undefined Even ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...