Tommy
Tommy

Reputation: 719

solution for error message "NgFor only supports binding to Iterables such as Arrays" not working

In my angular app I want to show a list of products the user can select.

So in my html file, I wrote the following code:

<section fxLayout="column" fxLayoutAlign="center center">
      <mat-selection-list #products>
        <mat-list-option *ngFor="let product of products">
            {{product.name}}
        </mat-list-option>
      </mat-selection-list>
</section>

In the .ts file, I have the following code:

  products;


  constructor(private productService: ProductService) { }

  ngOnInit() {
    this.loadAll();
  }


  private loadAll(): Promise<any> {
    this.products = [];
    return this.productService.getAll()
    .toPromise()
    .then((result) => {
        result.forEach(product => {
          this.products.push(product);
        });
    })
    .catch((error) => {     
        console.log(error);
    });
  }

I'm getting the following error message:

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

The thing is: products is(!) an array.

Still, I'm getting this error message as if this.products were in fact not an array.

What's going on here?

Upvotes: 0

Views: 625

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222582

You're already having an array, so no need to convert to array again,

  result.forEach(product => {
          this.products.push(product);
  });
  this.products = Array.of(this.products); //remove this line

Upvotes: 1

Related Questions