WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Advanced · question 60 of 100

How do you implement server-side pagination, sorting, and filtering in Angular applications?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

To implement server-side pagination, sorting, and filtering in Angular applications, you will need to work with both the frontend (Angular) and the backend (your server-side technology, e.g., Node.js, Django, etc.). In this answer, I will provide a general overview of the steps required and then show examples in Angular and Node.js.

**Overview:**

1. Modify your server-side API to support pagination, sorting, and filtering. It needs to be able to accept query parameters and return appropriate data based on these parameters.

2. Create a service in Angular to call the API by providing the necessary query parameters.

3. Update your Angular component to handle user actions that trigger pagination, sorting, or filtering, and update the displayed data accordingly.

**Step 1: Modify your server-side API**

Here is an example of a simple REST API using Node.js and Express, which supports pagination, sorting, and filtering through query parameters (‘page‘, ‘pageSize‘, ‘sortBy‘, ‘sortOrder‘, and ‘filter‘). This example assumes you have a collection of ‘items‘ (e.g., in a database, an array, etc.).

const express = require('express');
const app = express();
const port = 3000;

app.get('/api/items', (req, res) => {
  // Extract query parameters
  const page = parseInt(req.query.page) || 1;
  const pageSize = parseInt(req.query.pageSize) || 10;
  const sortBy = req.query.sortBy || 'id';
  const sortOrder = req.query.sortOrder || 'asc';
  const filter = req.query.filter || '';

  // Filter items based on the filter query
  const filteredItems = items.filter(item => {
    return Object.values(item).some(value => value.toString().toLowerCase().includes(filter.toLowerCase()));
  });

  // Sort the items
  const sortedItems = filteredItems.sort((a, b) => {
    if (sortOrder === 'asc') {
      return a[sortBy] > b[sortBy] ? 1 : -1;
    } else {
      return a[sortBy] < b[sortBy] ? 1 : -1;
    }
  });

  // Paginate the items
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  const paginatedItems = sortedItems.slice(start, end);

  // Send the response
  res.json({
    data: paginatedItems,
    totalItems: filteredItems.length,
    currentPage: page,
    totalPages: Math.ceil(filteredItems.length / pageSize)
  });
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

**Step 2: Create a service in Angular**

Now, you need to create a service in Angular to call the modified API. Here’s an example ‘item.service.ts‘:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ItemService {
  private apiUrl = 'http://localhost:3000/api/items';

  constructor(private http: HttpClient) {}

  getItems(params: { page: number; pageSize: number; sortBy: string; sortOrder: string; filter: string; }): Observable<any> {
    return this.http.get(this.apiUrl, { params });
  }
}

**Step 3: Update your Angular component**

Finally, update your Angular component to use the new service and handle user actions that trigger pagination, sorting, or filtering. Here’s an example ‘item.component.ts‘:

import { Component, OnInit } from '@angular/core';
import { ItemService } from '../services/item.service';

@Component({
  selector: 'app-items',
  templateUrl: './items.component.html',
  styleUrls: ['./items.component.css']
})
export class ItemsComponent implements OnInit {
  items = [];
  currentPage = 1;
  pageSize = 10;
  sortBy = 'id';
  sortOrder = 'asc';
  filter = '';

  constructor(private itemService: ItemService) {}

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

  getItems(): void {
    this.itemService
      .getItems({
        page: this.currentPage,
        pageSize: this.pageSize,
        sortBy: this.sortBy,
        sortOrder: this.sortOrder,
        filter: this.filter
      })
      .subscribe((response) => {
        this.items = response.data;
        // Handle other data (totalItems, totalPages) as required
      });
  }

  onPageChange(page: number): void {
    this.currentPage = page;
    this.getItems();
  }

  onSortChange(event: { sortBy: string; sortOrder: string }): void {
    this.sortBy = event.sortBy;
    this.sortOrder = event.sortOrder;
    this.getItems();
  }

  onFilterChange(filter: string): void {
    this.filter = filter;
    this.getItems();
  }
}

And a simple example for ‘items.component.html‘:

<!-- Pagination, sorting, and filtering UI goes here. It should interact with the Angular component variables and methods, for example: -->

<input [(ngModel)]="filter" (ngModelChange)="onFilterChange($event)" placeholder="Search..." />

<!-- Display items -->

<ul>
  <li *ngFor="let item of items">{{ item.name }}</li>
</ul>

<!-- Pagination buttons go here, for example: -->

<button (click)="onPageChange(currentPage - 1)" [disabled]="currentPage === 1">Previous</button>
<span>Page {{ currentPage }}</span>
<button (click)="onPageChange(currentPage + 1)" [disabled]="/* check if last page */">Next</button>

Now, your Angular application should display items based on the current pagination, sorting, and filtering settings, and the item list should update as these settings change. This server-side approach reduces the load on the frontend, improving performance when working with large datasets.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics