Displaying the content of the subarray

I am attempting to showcase the data stored in the array products from home.ts on the home.html file.

export class HomePage {
  public products: any[] = [
    {
      theater: {
        '30': {
          id: '44',
          name: 'product 30',
        },
      },
      party: {
        '31': {
          id: '45',
          name: 'product 45',
        },
        '32': {
          id: '46',
          name: 'product 46',
        },
      },
    },
  ];

  constructor(
    public navCtrl: NavController,
    public alertCtrl: AlertController
  ) {}
}

interface userData {
  name: string;
  email: string;
  testType: string;
}

Here is the code snippet from home.html:

<div *ngFor="let product of products[0]">

  <ion-card style="padding:0; margin:0; border-radius: 0; border-bottom: solid rgb(215, 215, 215) 1px;" *ngFor="let product of category">
    <ion-card-content style="padding:0; margin:0;">
      <ion-list>
        <ion-item lines="none" style="color: black;">
          <ion-thumbnail slot="start">
            <img alt="Silhouette of mountains" src="https://ionicframework.com/docs/img/demos/thumbnail.svg" style="border-radius: 50%;" />
          </ion-thumbnail>
          <ion-label>
          <p style="font-weight: 800; color: black;">Name: {{category.name}}</p>
          <p style="color: black;">31/12 às 22hrs</p>
          <p style="font-style: italic; color: black;">Cachaçamba,</p> 
          <p style="color: black;">Rio Verde - GO</p>           
        </ion-label>      
        </ion-item>
      </ion-list>
    </ion-card-content>
  </ion-card>

</div>   

Unfortunately, I am encountering an error:

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

Could you suggest a better approach to display the sub array based on the key's value party?

You can view my code on: stackblitz

Answer №1

To iterate through the object in Angular using *ngFor, you can utilize the KeyValuePair. However, do keep in mind that this method is only compatible with Angular 6 and above.

I suggest transforming the products array into an array of objects that are more convenient to manipulate.

[
    {
        "category": "theater",
        "data": [
            {
                "categoryId": "30",
                "product": {
                    "id": "44",
                    "name": "product 30"
                }
            }
        ]
    },
    {
        "category": "party",
        "data": [
            {
                "categoryId": "31",
                "product": {
                    "id": "45",
                    "name": "product 45"
                }
            },
            {
                "categoryId": "32",
                "product": {
                    "id": "46",
                    "name": "product 46"
                }
            }
        ]
    }
]

The code below demonstrates the transformation of the key-value pair array into nested arrays, followed by the flattening of these arrays.

formattedProducts: any[] = this.products
    .map((x) =>
      Object.entries(x).map((cat) => ({
        category: cat[0],
        data: Object.entries(cat[1]).map((y) => ({
          categoryId: y[0],
          product: y[1],
        })),
      }))
    )
    .reduce((acc: any[], cur) => acc.concat(cur), []);

Remember to adjust the HTML to accommodate the formattedProducts data.

<ion-content *ngFor="let category of formattedProducts">
  <ion-card
    style="
      padding: 0;
      margin: 0;
      border-radius: 0;
      border-bottom: solid rgb(215, 215, 215) 1px;
    "
    *ngFor="let cat of category.data"
  >
    <ion-card-content style="padding: 0; margin: 0">
      <ion-list>
        <ion-item lines="none" style="color: black">
          <ion-thumbnail slot="start">
            <img
              alt="Silhouette of mountains"
              src="https://ionicframework.com/docs/img/demos/thumbnail.svg"
              style="border-radius: 50%"
            />
          </ion-thumbnail>
          <ion-label>
            <p style="font-weight: 800; color: black">Name: {{cat.name}}</p>
            <p style="color: black">31/12 às 22hrs</p>
            <p style="font-style: italic; color: black">Cachaçamba,</p>
            <p style="color: black">Rio Verde - GO</p>
          </ion-label>
        </ion-item>
      </ion-list>
    </ion-card-content>
  </ion-card>
</ion-content>

Check out the Demo on StackBlitz

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 does `(keyof FormValues & string) | string` serve as a purpose for?

Hey there! I'm new to TypeScript and I'm a bit confused about the purpose of (keyof FormValues & string) | string. Can someone please explain it to me? export type FieldValues = Record<string, any>; export type FieldName<FormValues ...

Is there a different term I can use instead of 'any' when specifying an object type in Typescript?

class ResistorColor { private colors: string[] public colorValues: {grey: number, white: number} = { grey: 8, white: 9 } } We can replace 'any' with a specific type to ensure proper typing in Typescript. How do we assign correct ...

Typescript - filtering out null values from JSON object

I am facing an issue with my service method that saves a date on the server. When this method sends the date to the server, it includes fields with null values in the JSON. How can I exclude these fields with null values? public create<T>(post: any) ...

Information obtained from the visible is consistently indefinable

I provide a service that returns observables of an array of objects allItems: Item[] = [ { id: "1", name: "item 1" }, { id: "2", name: "item 2" }, { id: "3" ...

There is no index signature that accepts a parameter of type 'string' in the type '{ [key: string]: AbstractControl; }'

I'm currently tackling a challenge in my Angular project where I am creating a custom validator for a reactive form. However, I've encountered an error within the custom validators function that I am constructing. Below you will find the relevan ...

A Comprehensive Guide to Exporting Coverage Reports for Visual Studio Code Extensions

While searching for tutorials on creating vscode extensions, I came across various resources like: https://code.visualstudio.com/docs/extensions/testing-extensions There are plenty of tutorials on coverage exports, each suggesting different methods. Howe ...

Can anyone provide guidance on incorporating jQuery typing into an angular2 seed project?

I'm struggling to incorporate jQuery typings into my Angular2-seed project. Within my component, I am utilizing jQuery in the following manner: declare let $: any; export class LeafletComponent implements OnInit { ngOnInit(): void { th ...

Tips for using MatTableDataSource in a custom Thingsboard widget

After creating multiple custom Thingsboard widgets, I've discovered that I can access a significant portion of @angular/material within my widget code. While I have successfully implemented mat-table, I now want to incorporate pagination, filtering, a ...

Issue with displaying selected value and options in Mat-select when using formarray - Reactive forms in Angular

I've been working on the code below to create dropdowns, but I'm having trouble getting the selected value and options to show up in the dropdowns. Can you help me figure out what's wrong with the code? Component code testForm: FormGroup; ...

Typescript: requirement appears to be unmet

While compiling my Angular project, I encountered an error related to a package installed via NPM: node_modules/astrocite-ris/index.d.ts:36:39 - error TS2503: Cannot find namespace 'CSL'. The package named Astrocite contains a subpackage calle ...

Error Encountered: ExpressionChangedAfterItHasBeenCheckedError in Shared Service

Why am I receiving a warning in the console even though everything seems to be functioning correctly in Angular? How can this issue be resolved? You can find the StackBlitz here I understand that one possible solution is to use parent-child communication ...

Creating a Jira-inspired table layout in Angular by embedding components in a structured format

I'm attempting to recreate the functionality of Jira where I can create a "gadget" that can be added to a board, resized, moved, and deleted. (For those unfamiliar with why this might be useful, think of gadgets like the "Gantt" gadget. You can add a ...

Discovering all the specifics of a data type within VSCode's popup feature by hovering over a variable

Hovering over a TypeScript variable in VSCode displays the type definition in a popup. However, for complex types, the popup may not show the full definition and instead use an ellipsis to shorten it. Is there a way to view the entire type definition? ...

Allow users to zoom in and out on a specific section of the website similar to how it works on Google Maps

I am looking to implement a feature on my website similar to Google Maps. I want the top bar and side bars to remain fixed regardless of scrolling, whether using the normal scroll wheel or CTRL + scroll wheel. However, I would like the central part of the ...

Encountered an error while attempting to upgrade to the latest @angular/cli version 1.0.0: Unexpected symbol "<" found in JSON at the beginning of the file

When I was using angular-cli 1.0.0 beta 23, my service was able to fetch a local JSON file for testing without any issues. However, after upgrading to angular/cli 1.0.0, I encountered the following problem: GET http://localhost:4200/json/inputInventory/ ...

Set up SystemJS to properly load my Angular 2 component module

Recently, I made the switch from ng1 to ng2. I successfully imported Angular 2 and its modules into my project: <script src="/node_modules/systemjs/dist/system.src.js"></script> <script src="/node_modules/rxjs/bundles/Rx.js"></script& ...

Finding it challenging to adapt an AngularJs component-based modal to TypeScript

When creating an AngularJS component in JavaScript and displaying it as a modal using ui-bootstrap, you need to pass bindings that the modal instance can use for dismissing or closing itself: app.component("fringeEdit", { controller: "FringeEditCont ...

Switch from flexbox layout to begin on the next column within the same row

I am attempting to create a CSS layout where, after a specific element like :nth-child(6), the elements will break and form a separate column within the same row. The parent element should split into 2 columns after every 6th element in the same row, then ...

TypeScript observable variable not defined

Recently, I encountered an issue and made a change to resolve it. However, I am unsure if it is the correct approach... In my project, I have defined an interface: export interface ContextEnvironment { language: string; pingUrl: string; sessionFini ...

What is the best way to perform a deep copy in Angular 4 without relying on JQuery functions?

Within my application, I am working with an array of heroes which are displayed in a list using *ngFor. When a user clicks on a hero in the list, the hero is copied to a new variable and that variable is then bound to an input field using two-way binding. ...