Home > Software design >  Iterating *ngFor in Ionic
Iterating *ngFor in Ionic

Time:07-28

Try to iterate an array using *ngFor but it's not worked. below is my code.

My API Data showing like this in console widow

TypeScript Code

  tailors: Tailors[] = [];

  getTailors() {
    this.tailorService.getTailors().subscribe(x => {
      Object.assign(this.tailors, x);
      console.log(x);
    });
  } 

HTML

<ion-item  *ngFor="let tailor of tailors">
  <div >
   
    <div >
      <h3>{{tailor.data.Name}}</h3>
    
    </div>
  </div>
</ion-item> 

CodePudding user response:

Your bounded property in the *ngFor is an object literal not an array. You have to loop through tailors['data'].

I assume you have an error stating "NgFor only supports binding to Iterables such as Arrays".

Your code in the template should be

*ngFor="let tailor of tailors['data']"

Or better when you assign the backend response inside the .ts you bind the tailors to x['data'] and then you do not need to change anything in the template.

PS: I do not see a need of your usage of Object.assign(). Also include errors in your next posts to help people help you.

CodePudding user response:

You need to access data from x, and assign that to this.tailors.

getTailors() {
    this.tailorService.getTailors().subscribe(x => {
      // Object.assign(this.tailors, x); <- this won't work

      // This is because tailors needs to be an array, not an object.
      this.tailors = x['data'];
      console.log(x);
    });
  }
  • Related