Loop through object properties with *ngFor

Seeking suggestions on how to iterate over object keys in HTML using *ngFor within Angular 12. The provided data structure is as follows:

{
  "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
      }
    }
  ]
}

Answer №1

Check out the code on Stackblitz

Utilize RxJs to transform data for use in template rendering

@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;
    })
  );
}

using

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

This same approach can be used for handling API responses.

Answer №2

The keyValue pipe is a useful tool for iterating through objects in HTML.

public itemsList: any[] = [];

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

<ng-container *ngFor="let item of itemsList | keyvalue">
   {{ item.value.name }}  // Displays student name
   {{ item.value.is_present }}  // Displays present flag
</ng-container>

More information about the keyvalue pipe can be found in the Angular docs here.

Thank you!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlock TypeScript code suggestions for extended objects

In my app, I use a configuration file named conf.ts to consolidate config values from other files for better organization. By merging these values, it becomes more convenient to access them using Conf.MY_LONG_NAMED_VALUE rather than Conf.SubCategory.MY_LON ...

Using RxJs: switchMap conditionally based on the emitted value being empty

Below is the code snippet I am currently dealing with: const id = 1; // id = 2 of([{id: 1, name: 'abc'}]).pipe( map(items => items.find(item => item.id === id)), switchMap(item => item ? of(item) : this.makeHttp ...

Setting up Windows authentication for an ASP.NET Core 6.0 and Angular project: A complete guide

Attempting to set up Windows authentication with the ASP.NET Core 6 Angular template. Here is the current configuration in use: The following configuration has been added to the program.cs file: // Add services to the container. builder.Services.AddContr ...

What causes the sudden change of the variable to 0 in C programming language?

When I was practicing basics, I wrote a code to ask for the user's name and then wanted to print the user's name character by character. Additionally, I planned to display the entire name, its length, and finally the even-numbered characters of t ...

When comparing the results of running the NextJS build file and VS Code locally, there are noticeable discrepancies in

I am encountering an issue with the .next/ build directory. After running npm run dev, I have a working version locally, but I didn't realize to test the build file before deployment. The problem came to my attention when trying to deploy the code o ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

Trouble with styling the Ngx-org-chart in Angular

I integrated the ngx-org-chart library into my Angular project, but I'm facing issues with the styles not applying correctly. Here are the steps I followed: I first installed the package using: yarn add ngx-org-chart Then, I added the ngx-org ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

Is it possible to incorporate advanced transitions and animations using Angular 4?

Looking to incorporate animations using Angular 4 only. I have tried implementing the following advanced animation but struggled with writing parallel div animations in Angular 4. I believe this can be achieved via CSS, but unsure how to do so in Angular 4 ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

Using Mat-Error for Two Way Binding leads to frequent triggering of ngModelChange事件

I am working with a mat input field that has two-way data binding using ngModel, and I want to add validation using mat-error and formControl. <mat-form-field [formGroup]="myForm"> <input matInput formControlName="myFormName" autocomplete="off" ...

Jasmine has detected an undefined dependency

Testing out the following code: constructor(drawingService: DrawingService) { super(drawingService); //... } private writeOnCanvas(): void { this.drawingService.clearCanvas(this.drawingService.previewCtx); this.drawing ...

Angular: verifying the presence of any of the ng-content slots supplied

I have a component template that contains several ng-content elements: <div class="form__general"> <ng-content select="[general]"></ng-content> </div> <div class="form__footer"> <ng-conte ...

What is happening inside this room? Exploring Python's for loop with several inclusions

While experimenting with loops in Python, I encountered an unexpected output. Here is the code snippet: >>> for i in [1,2,3], j in [4,5,6]: print(i, j) [1, 2, 3] 5 True 5 It seems that the True value sometimes turns into False: ...

Encountering notifications and issues pertaining to conflicting dependencies after integrating the angular-oauth2-oidc dependency into the package.json file

I am currently working on an Angular project and wanted to share my package.json file for reference: { "name": "angular.io-example", "version": "0.0.0", "description": "Example project from ...

The focus of the input is lost when the value is being edited, specifically in the case where ngFor and ng

I'm facing an issue with a simple list that binds two-way to a parameter hero in my hero.component.ts. Whenever I begin typing in the input field, it seems to lose focus and I have to click on it again. How can I ensure that users are able to edit th ...

The sequence of output in TypeScript when using Gulp is similar to running tsc with a tsconfig

After setting up a tsconfig file and successfully running the command-line tsc, I encountered an issue when using gulp-typescript with a tsconfig.json and outFile specified. The output ordering was different, and I have been unable to find a solution in Gu ...

Encountering a problem with ng serve while attempting to launch the project

I am completely new to Angular and recently installed the latest version of Node.js along with Angular CLI globally. I cloned a project from GitHub and attempted to run it using 'ng serve', but encountered an error message: https://i.sstatic.net ...

Chrome autocomplete behaves as if the input fields are disabled and cannot be clicked on

I am experiencing an unusual issue with autofill in Chrome. After logging in and then logging out of the app, the input fields (email, password) are auto-filled but appear to be frozen and unclickable. This problem does not occur every time; it only happe ...