Rajesh Kumar
Rajesh Kumar

Reputation: 303

how to remove this error NgFor only supports binding to Iterables such as Arrays

I have a function in my component as

  missionSelected(event){
    this.category = event.option.value.children;
    console.log(this.category);
  }

This console log i am getting as:

    (3) [{…}, {…}, {…}]

But as i am using this variable in my template as:

    <mat-list-option *ngFor="let cat of category" [value]="cat">
        <div>{{cat.name}}</div>
    </mat-list-option>

This one giving me error as:

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

I tried to reinitialize the same object in array variable but i am getting same error. Many ways i tried but not getting proper solution.

adding console screenshot

Upvotes: 0

Views: 1646

Answers (3)

Rajesh Kumar
Rajesh Kumar

Reputation: 303

Thank you so much for all answer but i only was doing the mistake here: in my template i am using reference #category which is same as my category variable as shown below:

<mat-selection-list #category [multiple]="false">           
<mat-list-option *ngFor="let cat of category" [value]="cat.value">
<mat-icon mat-list-icon>folder</mat-icon>             
<div mat-line>{{cat.name}}</div>          
</mat-list-option>
</mat-selection-list> 

I just changed that reference name from #category to #reffer and it worked.....

Upvotes: 0

Barremian
Barremian

Reputation: 31105

You either need to check in the template if the array is defined

<ng-container *ngIf="category">
  <mat-list-option *ngFor="let cat of category" [value]="cat">
    <div>{{cat.name}}</div>
  </mat-list-option>
</ng-container>

or initialize the array in the definition.

category: Array<any> = [];

Update: keyvalue pipe

I am not sure if you're actually looping through an array. If in any case it's an object, you could use keyvalue pipe with the *ngFor directive.

<mat-list-option *ngFor="let cat of category | keyvalue" [value]="cat.value">
  <div>{{cat.key}}</div>
  <div>{{cat.value}}</div>
</mat-list-option>

Upvotes: 2

Juan Antonio
Juan Antonio

Reputation: 2614

Maybe the problem is the initial value of category. Have you initialized it to [] for example? If the initial value is null or other object *ngFor can't work with it as the message says.

Upvotes: 0

Related Questions