How to use ngFor with multiple arrays or objects?

Suppose you have two arrays of objects, one containing information about employees and the other containing information about departments. You want to display a list of employees with their department names using ngFor loop. How to use ngFor loop to display data from multiple arrays or objects in Angular? We can use the zip operator…

By.

min read

Suppose you have two arrays of objects, one containing information about employees and the other containing information about departments. You want to display a list of employees with their department names using ngFor loop.

How to use ngFor loop to display data from multiple arrays or objects in Angular?

We can use the zip operator from the RxJS library to combine the two arrays into a single stream and then use the ngFor loop to iterate over the combined stream and display the data.

Let’s assume we have the following two arrays of objects in our component class:

export class AppComponent {
  employees = [
    { id: 1, name: 'John', departmentId: 1 },
    { id: 2, name: 'Jane', departmentId: 2 },
    { id: 3, name: 'Bob', departmentId: 1 },
    { id: 4, name: 'Alice', departmentId: 2 }
  ];

  departments = [
    { id: 1, name: 'Engineering' },
    { id: 2, name: 'Sales' }
  ];
}

We want to display a list of employees with their department names in our template.

Step 1: Import the zip operator from the RxJS library in your component class.

import { zip } from 'rxjs';

Step 2: Create a new observable stream by using the zip operator to combine the two arrays.

const data = zip(
  from(this.employees),
  from(this.departments)
);

Step 3: Iterate over the combined stream using the ngFor loop in your template.

<ul>
  <li *ngFor="let [employee, department] of data | async">
    {{ employee.name }} ({{ department.name }})
  </li>
</ul>

In this example, we’re using the async pipe to subscribe to the observable stream and render the template once the data is available.

By using the zip operator from the RxJS library, we can easily combine multiple arrays or objects into a single stream and use ngFor to iterate over the combined stream and display the data in our template.

Leave a Reply

Your email address will not be published. Required fields are marked *