*ngFor – How to sort the items in the loop?

Sorting is a common operation when working with arrays in JavaScript. Similarly, when working with the ngFor loop in Angular, we may need to sort the items in the loop based on a specific criterion. In this tutorial, we will explore how to sort items in the ngFor loop in Angular.

We have a list of products in a JSON array, and we want to display them in a table using the ngFor loop. We want to sort the products based on their price in ascending order.

Sample JSON:

[
  { "name": "Product A", "price": 20 },
  { "name": "Product B", "price": 15 },
  { "name": "Product C", "price": 25 },
  { "name": "Product D", "price": 10 }
]

To solve this problem, we can use the built-in sort method of the JavaScript array to sort the products based on their price before rendering them in the template. Here are the steps to implement this solution:

 

Step 1 – Create a new Angular project using the Angular CLI:

ng new ng-for-sort-tutorial

 

Step 2 – Navigate to the project directory and open the app.component.ts file. Replace the default code with the following code:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>Products</h1>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let product of products">
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
        </tr>
      </tbody>
    </table>
  `
})
export class AppComponent {
  public products = [
    { name: 'Product A', price: 20 },
    { name: 'Product B', price: 15 },
    { name: 'Product C', price: 25 },
    { name: 'Product D', price: 10 }
  ];
}

This code defines a component that displays a list of products in a table using the ngFor loop. The products array contains four product objects with name and price properties.

 

Step 3 – To sort the products based on their price, we need to modify the products array before rendering it in the template. We can do this by adding a new method to the AppComponent class that sorts the array based on the price property:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>Products</h1>
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let product of sortedProducts">
          <td>{{ product.name }}</td>
          <td>{{ product.price }}</td>
        </tr>
      </tbody>
    </table>
  `
})
export class AppComponent {
  public products = [
    { name: 'Product A', price: 20 },
    { name: 'Product B', price: 15 },
    { name: 'Product C', price: 25 },
    { name: 'Product D', price: 10 }
  ];

  public sortedProducts = this.products.sort((a, b) => a.price - b.price);
}

In this modified code, we added a new property sortedProducts to the AppComponent class that is initialized by sorting the products array based on the price property. We used the sort method of the array and passed a callback function that compares the price property of two objects and returns a negative, zero, or positive number based on their order.

 

Step 4 – Finally, we need to update the ngFor directive in the template to use the sortedProducts array instead of the original products array:

<tr *ngFor="let product of sortedProducts">

 

Step 5 – Save the file and start the development server using the following command:

ng serve --open

This will open the app in a web browser at http://localhost:4200. You should see a table displaying the products sorted by price in ascending order.

Conclusion:

In this tutorial, we learned how to sort items in the ngFor loop in Angular using the sort method of the JavaScript array. We used a sample problem of sorting a list of products based on their price in ascending order and provided a step-by-step solution using the AppComponent class and template.

Leave a Comment

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