Angular Material Table – Sample Code to implement search data in table


Sample code that includes a search bar and a button to perform searches:

Component Code (your-component.component.ts):

import { Component, OnInit, ViewChild } from '@angular/core'; import { MatPaginator, PageEvent } from '@angular/material/paginator'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html', styleUrls: ['./your-component.component.css'] }) export class YourComponent implements OnInit { displayedColumns: string[] = ['column1', 'column2', 'column3']; // Replace with your column names data: YourDataType[] = []; // Replace YourDataType with your data type pageSizeOptions: number[] = [5, 10, 25]; pageSize: number = 5; pageIndex: number = 0; totalItems: number = 0; searchInput: string = ''; // Input for search query @ViewChild(MatPaginator) paginator: MatPaginator; constructor() { } ngOnInit(): void { this.totalItems = yourDataArray.length; // Replace with the total number of items in your data array this.refreshData(); } onPageChange(event: PageEvent): void { this.pageSize = event.pageSize; this.pageIndex = event.pageIndex; this.refreshData(); } refreshData() { const startIndex = this.pageIndex * this.pageSize; const endIndex = startIndex + this.pageSize; // Apply search filter if a search query is entered const filteredData = this.searchInput ? yourDataArray.filter(item => item.column1.includes(this.searchInput) || item.column2.includes(this.searchInput) || item.column3.includes(this.searchInput) ) : yourDataArray; this.totalItems = filteredData.length; this.data = filteredData.slice(startIndex, endIndex); } onSearch(): void { this.pageIndex = 0; // Reset to the first page when performing a new search this.refreshData(); } }

HTML Template (your-component.component.html):

<div> <mat-form-field appearance="fill"> <input matInput [(ngModel)]="searchInput" placeholder="Search"> </mat-form-field> <button mat-raised-button color="primary" (click)="onSearch()">Search</button> </div> <mat-table> <!-- Define your table columns here --> </mat-table> <mat-paginator [length]="totalItems" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions" (page)="onPageChange($event)"> </mat-paginator>

Summary:

  • Added a search bar (<mat-form-field>) and a search button (<button>) to the HTML template.
  • Added searchInput property to the component to store the search query.
  • Updated the refreshData function to apply a search filter to the data when a search query is entered.
  • Added an onSearch function to handle the search button click and refresh the displayed data based on the search query.
  • The pagination controls remain the same, and the search feature works alongside the pagination.