Home > Net >  Iterate object keys using *ngFor
Iterate object keys using *ngFor

Time:12-20

How to iterate over object keys on HTML using *ngFor in Angular 12. The response as below. Please suggest.

{
  "data": [
    {
      "student1": {
        "name": "Jhon",
        "present": false
      },
      "student2": {
        "name": "Bill",
        "present": true
      },
      "student3": {
        "name": "Keth",
        "present": true
      },
      "student4": {
        "name": "Anna",
        "present": true
      },
      "student5": {
        "name": "Vendy",
        "present": false
      },
      "student6": {
        "name": "Tim",
        "present": true
      },
      "student7": {
        "name": "Ron",
        "present": false
      }
    }
  ]
}

CodePudding user response:

Stackblitz

Use RxJs to map to data to be consumed in template

@Component({
  selector: 'my-app',
  template: `
    <table>
      <tr *ngFor="let student of data$ | async">
        <td>{{student.id}}</td>
        <td>{{student.name}}</td>
        <td>{{student.present}}</td>
      </tr>
    </table>
  `,
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular '   VERSION.major;

  data$ = of(DATA).pipe(
    map((value) => value.data[0]),
    map((obj) => {
      let arr = [];
      for (const id of Object.keys(obj)) {
        arr.push({
          id,
          name: obj[id].name,
          present: obj[id].present,
        });
      }
      return arr;
    })
  );
}

with

const DATA = {
  data: [...]
}

Same principle applies to response from api.

CodePudding user response:

keyValue pipe is used for iterate object into html.

public listItems: any[] = [];

ngOnInit() {
   this.http.getData().subscribe(res => {
       this.listItem = res?.data || []; 
   });
}

<ng-container *ngFor="let item of listItems | keyvalue">
   {{ item.value.name }}  // It will display student name
   {{ item.value.present }}  // It will display present flag
</ng-container>

keyvalue pipe in angular docs https://angular.io/api/common/KeyValuePipe

Thanks!

  • Related