Guide to displaying a nested object in Angular 7

Within my object data, I have a nested structure-

    "data": {
        "serial": "123",
        "def": {
            "id": "456",
            "data": {
                "firstname": "abc",
                },
            "method": "post",
        },
        "ghi": {
            "id": "456",
            "data": {
                "amount": "3500.0",
                    },
            "method": "post",
            },
        "jkl": "done"
    }

I assigned this to the items object. Next, I attempted displaying it in my HTML component like so-

<div *ngFor="let item of items | keyvalue">
        <div>
            <div>{{item.key}}:{{item.value}}</div>
        </div>
</div>

However, the output appears as-

serial: 123
def: [object Object]
ghi:  [object Object]
jkl: done

Could someone kindly advise on how to properly display this nested object? Appreciate any assistance!

Answer №1

Instead of using ngFor, which is typically meant for arrays (which you don't have), consider revising your data structure. If it needs to remain an object, simply access the specific property like this: data.def.id, no need for ngFor.

Here's another example to retrieve the firstname:

{{data?.def?.data?.firstname}}

Answer №2

When dealing with objects, using *ngFor may not work exactly like it does with arrays. A possible workaround is to create a recursive function in your TypeScript file:

  expandObject(data: any): string[] {
    let stringArr = [];
    for (const prop in data) {
      if (data[prop] instanceof Object) {
        stringArr = stringArr.concat([`${prop}: `]).concat(this.expandObject(data[prop]));
      } else {
        stringArr.push(`${prop}: ${data[prop]}`);
      }
    }
    return stringArr;
  }

In your HTML file, you can then use this function like so:

<div *ngFor="let item of expandObject(data)">
    {{ item }}
</div>

This will display the following content on your page:

serial: 123
def:
id: 456
data:
firstname: abc
method: post
ghi:
id: 456
data:
amount: 3500.0
method: post
jkl: done

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

What are the steps to transpile NextJS to es5?

Is it possible to create a nextjs app using es5? I specifically require the exported static javascript to be in es5 to accommodate a device that only supports that version. I attempted using a babel polyfill, but after running es-check on the _app file, ...

What causes a standard React component with a default render prop to not pass PropTypes validation successfully?

I'm currently working on a React component with a render-prop that has a generic type. To improve usability, I want to set a default value for the render-prop. The code is functioning correctly, but during type-checking, I encountered a warning regard ...

Using dual index variables in Angular 4's ngFor loop for iterating through arrays

Is there a way to generate unique index numbers for items printed only on Saturdays? Specifically, I want the index to start from 0 once Saturday begins and continue incrementing. The rest of the options should have the same index numbers. Any suggestions ...

How to style a parent div with a background class in Angular 6

In my Bootstrap 4 project, I am creating an accordion that consists of cards. Each card contains various icons such as edit, view, and details. When any of these icons are clicked, a function in the component is triggered to navigate the user to a child ro ...

Ensure that you only run `npm publish` in the Angular monorepo if there

In my angular monorepo, I have an "app" and a library that is published as its own npm package. The publishing process is automated on a CI environment. Previously, the library and app had separate build jobs. Now that they are built together, I am encount ...

Issue: The CSS loader did not provide a valid string output in Angular version 12.1.1

I am encountering 2 error messages when trying to compile my new project: Error: Module not found: Error: Can't resolve 'C:/Users/Avishek/Documents/practice/frontend/src/app/pages/admin/authentication/authentication.component.css' in &apos ...

Issue with updating view in React Native/Javascript after an asynchronous fetch operation. Execution order may be invalid

Below is the code I've written to fetch data using fetch() and display an output only after fetching it. However, the view fails to update after the asynchronous call. Since I'm new to react native async calls, I would appreciate some help on thi ...

Is there a way to customize the language used for the months and days on the DatePicker

Is there a way to change the language of the DatePicker (months and days) in Material UI? I have attempted to implement localization through both the theme and LocalizationProvider, but neither method seems to work. Here are some resources I have looked a ...

Boost the Gen 2 User Directory

After reviewing all of the Amplify Gen 2 Documentation, I am struggling to find a way to display a list of registered users within my application. I need to create an admin page in Angular that will showcase all users along with their respective roles. I ...

What is the best way to incorporate a cancel button in an Angular application?

Imagine a situation where the man has input some information. <input type="text" name="text" [(ngModel)]='project.text'> Now, if someone needs to delete or modify this data. How would you go about adding a button that can cancel all chan ...

Utilizing span elements to display error messages

Currently, I am using a directive on a field to prevent users from entering HTML tags and JavaScript events. However, I am encountering a few challenges: a) My goal is to display an error message immediately when a user tries to input HTML tags or JavaScr ...

Redux dealing with collections of objects and searching through deeply nested objects

Being new to React and Redux, I am seeking a cleaner and more efficient way to structure my state. Currently, my state is organized as follows: --Character ---id ---name ---race ----id ----raceName ----traits -----trait ------id ------name ------descriptio ...

Incorporate TypeScript into your React projects for improved type

Currently, I am immersing myself in learning React with Typescript. One of the challenges I am facing is related to a specific view I have created. index.tsx import React from 'react' import { CButton } from '@coreui/react' import { us ...

What is causing JavaScript to pass the parameter name instead of the element?

Information: I am currently organizing an array of names into two separate arrays - one for names starting with A-M and the other for names starting with N-Z. My goal is to have each entry represented as an object with the name as the property and an empty ...

Can a string be used to reference a type in Typescript?

Consider this scenario: I have created a set of interfaces that define the entities within my system: interface Company { name: string } interface Employee { firstName: string lastName: string } Now, what I am looking for is a universal function th ...

Mixing pipe operators with Angular Observables in an array

In my project, I have an interesting scenario where I am using Observables and piping them to multiple functions as shown below. getOrders(filters: any, page: any = 1, orderBy: string = 'deliver_on', sort: string = 'asc') { const op ...

Converting any object into a List of integers: Step by step guide

What is the best way to convert an object into a list of bytes? Example: class MyClass {} var myClass = MyClass() List<int> convertObjectToListOfBytes(Object object) { // How should this be implemented? } // Usage example: List<int> byt ...

Encountering an issue in app.module.ts with Angular 6 when trying to pass an array of injectables to providers resulting in the error message: "Property 'length' of undefined cannot be read"

Below is an array containing injectables connected to services: import { YouTubeSearchService, YOUTUBE_API_KEY, YOUTUBE_API_URL } from './you-tube.service'; export const youTubeSearchInjectables: Array<any> = [ { provide: Yo ...

Utilize Redux in conjunction with TypeScript to seamlessly incorporate a logout feature

My login page redirects to a private /panel page upon successful login with an accessToken. I am utilizing the Redux store to verify the token in the privateRoute component. Challenges I'm encountering: I aim to enable logout functionality from t ...

Pause for a few moments until assigning a new value to the observable

In my application, I have implemented a message service that emits messages whenever the API method is triggered. The main purpose behind this is to allow all other components in the app to utilize the service for displaying error or success messages. imp ...