Home > Software engineering >  Angular: *ngFor iterate through Array Objects won't function
Angular: *ngFor iterate through Array Objects won't function

Time:08-07

i try to iterate trough my Array of data. Unfortunately i got no error message or anything like.

If i iterate trough an object i got still this error but elements got created:

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

For Fixxing this error i try to push the individual objects in 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 my problem is (i think), the objects get pushed into array index 0. Why does it do not the index ?

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

The HTML Part:

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

CodePudding user response:

For whatever reason your array doesn't include items that are iterable. Which is also confirmed by [[Prototype]]: Array(0). Your setting key : value in your array (which is invalid for an array, array can't hold keys, only items). If you want to have an Map in javascript it would need to be an object {}. My assumption is that data: any is an object and forEach works for objects, so when pushing item in array this.top3News.push(item);you're actually pushing 0: {id: 1, …}. However if you do need the items with keys you can iterate over objects in template using | keyvalue pipe.

So let's get rid of the keys and only push 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 }}" >
    </div>
</ng-container>

CodePudding user response:

After a while of reproducing, the problem is finally solved. I can now say the code was and is correct.

Almost shot myself in the leg for this....

  changeDetection: ChangeDetectionStrategy.OnPush,
  • Related