You are currently viewing Angular 9 and Spring Boot CRUD Tutorial – Feature 6 sort expenses by name and amount

Angular 9 and Spring Boot CRUD Tutorial – Feature 6 sort expenses by name and amount

Hey in the previous post we discussed filtering expenses based on keyword, in this post, we will sort the expenses by expense name and amount. We will sort the expense name in ascending order and amount in descending order. So let’s begin…




In this post, we will cover the following topics,

  • Javascript sort() method
  • Method chaining

Obviously our first step is to create a dropdown list inside the list-expenses.component.html with two options, Name and Sortby for sorting the expenses.

<div class="row">
    <div class="col-md-4">
        <input type="text"
            [(ngModel)]="filters.keyword"
            name="keyword"
            (input)="listExpenses()" 
            class="form-control"
            placeholder="Filter expense"/>
    </div>
    <div class="col-md-4">
        <select name="sortBy" 
                [(ngModel)]="filters.sortBy" 
                (change)="listExpenses()"
                class="form-control">
            <option>Name</option>
            <option>Amount</option>
        </select>
    </div>
    <div class="col-md-4">
        <a class="btn btn-primary text-light" routerLink="/addexpense">Add Expense</a>
    </div>
</div>
<div>
    <div class="card mt-1" *ngFor="let expense of expenses">
        <a routerLink="/editexpense/{{expense.id}}" class="card-body flex">
            <span class="text-capitalize font-weight-bold">{{expense.expense}}</span>
            <span class="float-right mr-2 badge badge-pill badge-warning font-weight-bold amount">{{expense.amount | currency: 'INR'}}</span>
        </a>
        <div class="card-footer">
            <button class="btn btn-danger" (click)="deleteExpense(expense.id)" style="width: 10%;">Delete</button>
        </div>
    </div>
</div>

If you notice we are using NgModel for two-way data binding. Also, we are wiring up the change event to the call listExpenses() method.




We will sort the expenses inside the filterExpenses() which is defined in the list-expenses.component.ts file, we will chain the sorting logic for the filtered expenses.

import { Component, OnInit } from '@angular/core';
import { Expense } from 'src/app/models/expense';
import { ExpenseService } from 'src/app/services/expense.service';


@Component({
  selector: 'app-list-expenses',
  templateUrl: './list-expenses.component.html',
  styleUrls: ['./list-expenses.component.css']
})
export class ListExpensesComponent implements OnInit {

  expenses: Expense[] = [];

  filters = {
    keyword: '',
    sortBy: 'Name'
  }

  constructor(private _expenseService: ExpenseService) { }

  ngOnInit(): void {
    this.listExpenses();
  }

  deleteExpense(id: number) {
    this._expenseService.deleteExpense(id).subscribe(
      data => {
        console.log('deleted response', data);
        this.listExpenses();
      }
    )
  }

  listExpenses() {
    this._expenseService.getExpenses().subscribe(
      data => this.expenses = this.filterExpenses(data)
    )
  }

  filterExpenses(expenses: Expense[]) {
    return expenses.filter((e) => {
      return e.expense.toLowerCase().includes(this.filters.keyword.toLowerCase());
    }).sort((a, b) => {
      if (this.filters.sortBy === 'Name') {
        return a.expense.toLowerCase() < b.expense.toLowerCase() ? -1: 1;
      }else if(this.filters.sortBy === 'Amount') {
        return a.amount > b.amount ? -1: 1;
      }
    })
  }
}

That’s it for the sorting, now if you run the application, you will see the dropdown inside the list expenses page and you can sort the expenses based on expense name and amount.







You can find the Github repository here

You can find the step by step video series here

 

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

This Post Has 2 Comments

  1. Mayur

    Getting Error in the Feature 6

    Argument of type ‘(a: Expense, b: Expense) => 1 | -1 | undefined’ is not assignable to parameter of type ‘(a: Expense, b: Expense) => number’.
    Type ‘number | undefined’ is not assignable to type ‘number’.
    Type ‘undefined’ is not assignable to type ‘number’.

    44 }).sort((a, b) => {
    ~~~~~~~~~~~

    1. AIGRON

      The error “Not all code paths return a value” occurs when some of the code paths in a function don’t return a value. To solve this error, in this tuto make sure to set noImplicitReturns to false in your tsconfig.json file.

Leave a Reply