How to efficiently display nested object data using Angular Keyvalue pipe

I am facing an issue with a particular HTTP request that returns an observable object containing multiple properties. One of these properties is the 'weight' object which has two key values, imperial and metric.

While attempting to loop through the key values of this object, I encountered difficulties rendering the nested objects as it only displays:

weight [object object]

This is the code snippet I used:

<div style=" margin : auto; border : 1px solid black; width : 70%; ">
<div style="display : flex;  justify-content : space-around; flex-wrap:wrap;">
  <div *ngFor="let breed of (breeds$ | async )" style="flex : 33%">
  <div *ngFor="let item of (breed | keyvalue : unsorted)">
    <div *ngIf="item.key === 'weight'">
      {{breed.weight.imperial}}
    </div>
    <b>{{item.key}}</b>{{item.value}}
  </div>
  </div>
</div>

My current approach seems to be limited and ineffective for handling other objects within the observable data. It also does not seem like the most optimal solution.

Here is an example of the data returned by the observable:

    {
        "weight": {
            "imperial": "7  -  10",
            "metric": "3 - 5"
        },
        "id": "abys",
        "name": "Abyssinian",
        "image": {
            "id": "0XYvRd7oD",
            "width": 1204,
            "height": 1445,
            "url": "https://cdn2.thecatapi.com/images/0XYvRd7oD.jpg"
        }
    }

In an attempt to rectify the issue, I replaced my previous explicit approach with:

<div *ngIf="item.key === 'weight'">
<div *ngFor="let data of item.value">{{data.imperial}}</div>
</div>

Unfortunately, this resulted in the following error message:

Type 'string | number | { imperial: string; metric: string; } | { id: string; width: number; height: number; url: string; }' is not assignable to type '(string & NgIterable<string>) | null | undefined'.ngtsc(2322)

Answer №1

To iterate over the object, use the keyvalue pipe on the weight object.

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

Check out the demo on StackBlitz

Answer №2

Encountered the same issue, but managed to find a solution.

Take a look at this stackblitz for guidance.

Create a compare function for keyValue and specify the parameter type as KeyValue<string, any>

written in typescript

  ...

  sortByValueAsc = (a: KeyValue<string, any>, b: KeyValue<string, any>) => {
    return 0
  };

and in HTML

<td *ngFor="let answer of surveyDetail.answer | keyvalue:sortByValueAsc">{{answer.value?.level}}</td>

Answer №3

Consider implementing the following code snippet:

<div *ngFor="let type of types">

  <div>{{ type.size.small }}</div>

  <div>{{ type.size.large }}</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

Setting the location of the global nprmrc file on a Windows operating system

Is it possible to change the default global npmrc location in Windows operating systems? ...

Issues with Ionic's HTTP functionality are preventing it from working properly within

I'm encountering an issue with my function where ajax doesn't seem to work properly. Can someone please help me identify the problem? import { FormControl } from '@angular/forms'; import { Http } from '@angular/http'; export ...

What advantages do binary shifts offer in enums?

What do you think about this code snippet? /** * Bitmask of states */ export const enum ViewState { FirstCheck = 1 << 0, // result is 1 ChecksEnabled = 1 << 1, // result is 2 Errored = 1 << 2, // result is 4 ...

Showing user input in an Angular 2 component based on their selection in a dropdown menu

Inside a div element, there is a select tag which contains two options - New and Used. Following this are two div elements within a separate container that should be hidden based on whether New or Used is selected. Take a look at my code below and let me ...

How can I specify the type of an object in Typescript to mirror a class's properties as a list?

This demonstration is kept simplistic and straightforward, yet the ultimate objective is far more intricate. It is crucial to grasp the method behind achieving this. Let's assume there exists a class class Foo { bar: string; baz: number; bob: a ...

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...

I'm encountering an issue with my array in JavaScript while using // @ts-check in VS Code. Why am I receiving an error stating that property 'find' does not exist on my array? (typescript 2.7

** update console.log(Array.isArray(primaryNumberFemales)); // true and I export it with: export { primaryNumberFemales, }; ** end update I possess an array (which is indeed a type of object) that is structured in the following manner: const primar ...

Encountering an unexpected closing tag "a" while using Angular 2 with webpack

I am currently working with an Angular 2 template that displays tabs on my website: <div id="menu"> <ul id="tabs"> <li *ngFor="let tab of tabs; let i = index" [class.active]="selectedTab===i"> <a routerLink="/p ...

When I run ng build, an error code ".form-floating>~label" pops up

After running the command "ng build" in my Angular app, I encountered the following output: ✔ Browser application bundle generation complete. ✔ Copying assets complete. ⠋ Generating index html...4 rules skipped due to selector errors: .form-floatin ...

Guide on utilizing the h function in Vue3 for seamless binding and passing of properties and events from parent to child components

Utilizing Vue3 and naive ui for front-end development has been a challenge for me as I primarily focus on back-end development and lack expertise in front-end technologies. To enhance user interaction, I incorporated naive ui’s BasicTable along with an ...

Tips for mocking Dependent Modules in Jasmine when dealing with a plethora of dependencies in Angular 9

Looking to create a unit test for a component within an Angular project. The main component has 5-6 dependencies and extends another class with around 7 additional dependencies. What is the most effective method to set up the TestBed for this component? ...

Save this code snippet to your clipboard using vanilla JavaScript (no jQuery needed)

I am working on an Angular 9 application where I want to implement the functionality of copying the URL to clipboard when clicked. Currently, I have the following code: The issue I am facing is that it only copies the URL on the second attempt and then st ...

How can one effectively access a nested JSON value in Angular by concatenating all fields?

If we have a JSON stored in the variable person like below: { "firstName": "First Name", "lastName": "Last Name", "address": { "city": "New-York", "street": "Some Street" } } To access the value of street, we would typical ...

What is the most recent stable version of Angular recommended for utilizing ui-bootstrap?

I've been working on updating an older angular application and I'm interested in incorporating ui bootstrap for more advanced features. However, the current version of Angular used is 1.2.18 and any attempt to upgrade it to a higher version resul ...

retrieving information and parsing from an API using Ionic and Angular version 4

How can I extract data from the "data" field in my API using a function? getMenu() { return this.http.get('http://site.dev/api/menu/7'); } { "id": 26, "name": "Default", "title": "default", "pageelements": [ { "id": 15, ...

I'm curious about why the value of my variable in service.ts keeps changing whenever the page is refreshed?

Below is my Angular service.ts file code. It is used to store the login status. import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) e ...

Why am I struggling to show the success message on my basic CRM Angular web application?

I'm facing an issue in my Basic Angular app where the success message is not being displayed even after writing the correct code. 1)app.component.html <h1 class="c1">{{title}}</h1> <div *ngIf="success_msg;" style=&q ...

Using Typescript to define the type for React's useState() setter function whenever

I'm working on setting up a React Context to handle parameters mode and setMode, which act as getter and setter for a React state. This is necessary in order to update the CSS mode (light / dark) from child components. I'm encountering a Typescr ...

Troubleshooting issue with Angular-CLI and Cordova plugin integration

While attempting to build an Angular 4 app using ng-build, I encountered an error when trying to access device.uuid: /navigation.component.ts (14,5): Cannot find name 'device'. Every plugin referenced in TS files is triggering this error. I a ...