Angular: Issue with *ngFor not iterating through Array Objects

I have been attempting to iterate through my array of data, but I am not receiving any error messages or feedback at all.

When I try to iterate through an object, I encounter the following error message, but the elements are still being created:

Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'.

To fix this error, I am trying to push the individual objects into an array.

export interface iProjectNewsData {
  id: number;
  ....
}

    
export class ProjectNewsComponent implements OnInit {
top3News: iProjectNewsData[] = [];

constructor(
  ....
  private projectNewsService: ProjectNewsService
) {
  this.projectNewsService.fetchTop3News().subscribe((data: any) => {
    data.forEach((item: iProjectNewsData) => {
      this.top3News.push(item);
    });
  });
}

Now, I believe the problem is that the objects are being pushed into array index 0. Why is it not incrementing the index?

[]
  0: {id: 1, …}
  1: {id: 2, …}
  2: {id: 3, …}
  length: 3
  [[Prototype]]: Array(0)

The HTML section:

<ng-container>    
    <div *ngFor="let news of top3News" [ngModel]="top3News" name="Top3NewsElement" ngDefaultControl>
       <img src="/assets/images/project-news/{{ news.image }}" class="w-full h-full rounded-top">
    </div>
</ng-container>

Answer №1

It seems that your array does not contain iterable items, as indicated by [[Prototype]]: Array(0). Assigning key : value pairs in the array is invalid, as arrays can only hold items. If you wish to use a Map in JavaScript, you should use an object {}. Based on the assumption that data: any is an object and forEach works for objects, when you push an item into the array with this.top3News.push(item);, you are actually pushing 0: {id: 1, …}. If you do require items with keys, you can iterate over objects in the template using the | keyvalue pipe.

To address this, let's remove the keys and only push the values v = {id: 1, …}.

  this.projectNewsService.fetchTop3News().subscribe((data: any) => {
    for (const [k, v] of Object.entries(data)) {
      this.top3News.push(v);
     }
  });
<ng-container>    
    <div *ngFor="let news of top3News">
       <img src="/assets/images/project-news/{{ news?.image }}" class="w-full h-full rounded-top">
    </div>
</ng-container>

Answer №2

After much persistence, the issue has been successfully resolved. I am confident in saying that the code was indeed accurate.

That was a close call...

  changeDetection: ChangeDetectionStrategy.OnPush,

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

The debate between TypeScript default generic types and contextual typing

Contextual Typing in TypeScript is an interesting feature where the correct type is inferred from the return value when a generic type is not specified. While it usually works well, there are instances where it can be unpredictable. For example, in some c ...

The error message "InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' in Angular 6 and Firebase" indicates a problem with the data being passed to the AsyncPipe in

**Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'. ** I am encountering a problem with unsubscribing from the observable. My Angular-cli version is 6.0.3 This is the HTML code in home.component.html <div class ...

Adding additional rows within an *ngFor loop can be achieved by dynamically updating the data source that the loop is iterating over. By manipulating the data structure

I am looking to add expand-collapse functionality to my tables using Angular 2. Specifically, I want the expanded portion to only show below the row that was clicked. I have attempted to achieve this with the code snippet below, but currently, the new row ...

Pushing out the both /browser and /server directories from an Angular SSR application to Azure Static Web Apps

Continuing from the discussion in this thread, my current challenge involves deploying my Angular SSR app to Azure SWA. I have successfully set it up for running and deployment (using the GitHub Action here): name: Azure Static Web Apps CI/CD on: push: ...

TypeScript React Object.assign method return type

I have a unique custom function that utilizes Object.assign to return a specific result. The documentation mentions that this function returns an array, but surprisingly, it can be destructured both as an array and an object. Check out the code snippet be ...

Tips on converting a date string in the format 'dd/MM/yyyy' to a date type using TypeScript

I have attempted the following code in order to convert the date from 'yyyy-mm-dd' format to 'dd/MM/yyyy'. However, when I check the typeof() of the result, it shows that it is a string. Is there a method to convert it into only a date? ...

Adjusting the audio length in React/Typescript: A simple guide

I'm currently developing a web app with React and TypeScript. One of the components I created is called SoundEffect, which plays an mp3 file based on the type of sound passed as a prop. interface ISoundEffectProps { soundType: string, // durat ...

Developing and employing Services in Angular 2

Having some trouble with Angular2 as I explore it for the first time, specifically in creating and using a service. I've set up a data service like this: import {Injectable} from 'angular2/core'; import {recentActivity} from './app/com ...

Ways to check my component using ActivatedRoute?

I am currently facing an issue while testing a component that utilizes two resolvers (pagesResolver and UploadResolver): Below is the code snippet for my component: export class AdminPagesComponent implements OnInit { fileUploads$: Observable<FileUpl ...

The element does not have a property named "emit" in its type

Trying to transfer data between components using Subject through services resulted in the error message below: 'Property 'emit' does not exist on type 'Subject(any)'. This is what was attempted: component.ts file import { Compo ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Exploring the use of Jest for testing delete actions with Redux

I've been working on testing my React + Redux application, specifically trying to figure out how to test my reducer that removes an object from the global state with a click. Here's the code for my reducer: const PeopleReducer = (state:any = init ...

Unable to modify data with ionic and firebase in child node format

I am encountering an issue when updating data with Ionic Firebase using the following code. Instead of rewriting the previous data, it simply creates new data entries. Here is the code snippet: updateLaporan() { this.id =this.fire.auth.cur ...

Using a Typescript typeguard to validate function parameters of type any[]

Is it logical to use this type of typeguard check in a function like the following: Foo(value: any[]) { if (value instanceof Array) { Console.log('having an array') } } Given that the parameter is defined as an array o ...

Immediate update: Receiving a status of 400 "Bad request" when trying to make an HTTPPOST

After tirelessly searching through various online resources like Google and Stack Overflow to troubleshoot my code without success, I find myself resorting to posting a question here. The issue at hand involves two nearly identical functions in my service ...

Is it possible for me to create a CSS class based on a condition using [ngCLASS]?

I am struggling with logic writing in my Angular2 project. On a HTML page, I have two buttons - YES and NO that I want to style with different colors. I have set up a condition in the div tag like this: ngClass="'result'?'yes':' ...

Get rid of the box-shadow that appears on the top side of mat-elevation

I placed a mat-paginator at the bottom of my mat-table which is styled with a mat-elevation-z4 class. However, when I added the mat-elevation-z4 class to the mat-paginator component as well, the upper shadow from the paginator appears to overflow onto the ...

What other options exist besides RxJS operators?

Imagine a scenario like this: submit(): void { this.loading = true; dataLength?: number = untracked(this.dataService.data)?.length; this.dataService.addData(this.dataForm.value); effect( () => { if (this.dataLength !== thi ...

Managing the onChange event for a MaterialUI dropdown component

I'm encountering an issue with validating the MaterialUI TextField component (Country list) wrapped with Autocomplete. I am trying to use the onChange event to enable the Submit button when the country field is filled in. However, the problem arises w ...

What is the reason behind TypeScript indicating that `'string' cannot be assigned to the type 'RequestMode'`?

I'm attempting to utilize the Fetch API in TypeScript, but I keep encountering an issue The error message reads: Type 'string' is not assignable to type 'RequestMode'. Below is the code snippet causing the problem export class ...