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

What is the method for adjusting the time format?

Using the TIME data type, my data is currently displayed in the format hh:mm:ss (03:14:00). How can I change it to display in the format hh:mm (03:14)? The usual DATE type method does not seem to work: {{test.time | date: 'HH:mm'}} However, thi ...

Problem with Jasmine in Angular 5 within Visual Studio Code

I am completely new to Angular 5 Unit testing and facing some challenges. Despite installing all @types/jasmine, I am encountering errors in my spec.ts file such as 'describle is not a name' and 'jasmine.createSpyObj does not exist on the ty ...

How can I use Angular2 to draw a square [input] number of times?

I need to create a specific number of squares within a container using Angular2. Can you please provide me with a straightforward example, preferably utilizing canvas? Currently, I have converted webpack starter for use with Angular: This is the code ins ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

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 ...

ng-bootstrap Datepicker with current date displayed as a placeholder

I have been using ng-bootstrap Datepicker and have implemented it like demonstrated in this example on Plunker. <div class="input-group"> <input class="form-control" placeholder="yyyy-mm-dd" name="dp" [(ngModel)]="model" ngbDatepicker ...

The list in Ionic 3 search does not appear after clearing the search bar

Can anyone assist me with my search bar issue? I'm able to display words on the list, but once I clear the search bar, nothing shows up. Here is a snippet of my code: In my home.html file: <ion-searchbar (ionInput)="getItems($event)" [showCancelB ...

Choose a specific div element from a collection of dynamically generated divs in Angular

I have been working on a code to dynamically generate div elements using the *ngFor directive. Here is what I have so far: <div *ngFor = "let item of Items"> <p>Item : {{item}} </p> </div> The challenge I encountered is that w ...

Leveraging Google Analytics with Angular 4 and beyond

Having trouble integrating Google Analytics with Angular 4? Can't seem to find the @type for ga.js in ts? Here's a quick fix that I implemented in every component: declare let ga: any; How did I solve it, you ask? I created a function to dyna ...

Error: Unable to access $rootScope in the http interceptor response function

I have set up an interceptor to display an ajax spinner while loading. interface IInterceptorScope extends angular.IRootScopeService { loading: number; } export class Interceptor { public static Factory($q: angular.IQService, $ro ...

Creating an Excel file with Angular 6 using sheetJs and eliminating specific keys from the data

I have a JSON data structure that includes information about individuals and the cities they live in: [{"name":"peter", "surname":"cage", "nickname": "peterbob", "city":{"id":130, "name":"GreatCity"} }, {"name":"james", "surname":"parot", "nickname": "m ...

Position the dropdown beneath the button within the Chips Autocomplete component for proper alignment

I have enhanced the layout of the Chips Autocomplete component by placing a button above the dropdown, as illustrated in the image below. My goal is to position the dropdown below the button, similar to this desired arrangement. Though I have applied pad ...

What circumstances warrant the utilization of an Angular service?

My understanding is that services are utilized for inter and intra component communication to abstract complex data structures. Is it accurate to say that services are exclusively used for persistent data structures? In what scenarios should we avoid usi ...

Receiving NULL data from client side to server side in Angular 2 + Spring application

I'm currently working on a project that involves using Angular 2 on the client side and Spring on the server side. I need to send user input data from the client to the server and receive a response back. However, I'm encountering an issue where ...

What's the best way for me to figure out whether type T is implementing an interface?

Is it possible to set a default value for the identifier property in TypeScript based on whether the type extends from Entity or not? Here's an example of what I'm trying to achieve: export interface Entity { id: number; // ... } @Compon ...

Troubleshooting ngModel Binding Issue with Sub-Children in CKEditor 5 and Angular 7

Firstly, I am sharing my code below: ListPagesComponent: export class ListPagesComponent { public model = { id: -1, actif: 0, link: '', htmlContent: { fr: '', ...

angular 2 choose text feature

Is there a way in Angular 2 to retrieve the selected text from an option element? Especially considering I have multiple select elements dynamically generated. Do I need to store them in an array? And how do I go about retrieving the text for all of them, ...

Expanding TypographyProps and TextFieldProps for enhanced functionality

Currently, I am developing a React component using TypeScript along with Material UI (MUI). The main purpose of this component is to display either an input field or text based on the mode selected. To switch between these modes, the prop mode is utilize ...

Angular StrictNullChecks: "Error - object may be null"

I am encountering an issue with the 'strictNullChecks' setting in my Angular project. This has resulted in numerous errors across my templates (.html), such as: <input #inputValue type="text" (keyup.ent ...

What is the proper method for transferring a JWT token to an external URL?

I currently have two REST endpoints set up: accounts.mydomain.com/login - This is an identity provider that sends a JWT token as a response once a user is authenticated with their username and password. api.mydomain.com/users - This endpoint accepts the ...