How can I help you?
Searching in Angular Grid Component
19 Mar 202624 minutes to read
The Syncfusion Angular Grid includes a powerful built-in searching feature that enables efficient filtering of grid records based on search criteria. This feature allows quick discovery of specific data within large datasets. Whether the application works with small or large datasets, the search feature provides a seamless solution for locating relevant records instantly.
Enable searching
To use the searching feature, need to inject SearchService in the providers section.
In addition, a search text box can be placed directly in the grid toolbar to provide a convenient place to enter search criteria. This can be done by injecting the Toolbar module into the grid and configuring the toolbar property with Search item.
The following example demonstrates enabling the toolbar with search option in the grid:
import { data } from './datasource';
import { Component, OnInit } from '@angular/core';
import { GridModule, SearchService, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [ GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid [dataSource]='data' [toolbar]='toolbarOptions' height='272px'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='Freight' headerText='Freight' textAlign='Right' format='C' width=80></e-column>
<e-column field='OrderDate' headerText='Order Date' textAlign='Right' format='yMd' width=100></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
ngOnInit(): void {
this.data = data;
this.toolbarOptions = ['Search'];
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
- The clear icon is shown in the Grid search text box when it is focused on search text or after typing the single character in the search text box. A single click of the clear icon clears the text in the search box as well as the search results in the grid.
- In Syncfusion Grid component, searching operates independently for parent and child grids. Searching within the parent grid filters only parent records, and similarly, searching within the child grid filters only child records. The component does not support simultaneous searching across both parent and child grids.
Initial search
By default, the search operation is performed after the grid renders. However, scenarios may require applying a search automatically when the grid first loads. The initial search feature enables this by setting search criteria before the grid displays its data.
To apply search at initial rendering, need to set the following properties in the searchSettings object.
| Property | Description |
|---|---|
fields |
Specifies the fields (column names) in which the search operates. By default, the grid searches all columns. Set this property to limit the search to specific columns. |
operator |
Specifies the operator that determines the way the search key matches the data. Available Options include startswith, endswith, contains, equal, and others. The default value is contains. |
key |
Specifies the key value (search text) to be applied. The grid filters records matching this value based on the specified operator. |
ignoreCase |
Set ignoreCase to true to make the search case-insensitive. For example, searching “john” finds “John”, “JOHN”, and “john”. |
ignoreAccent |
Set ignoreAccent to true to ignore diacritic characters (accents) during searching. For example, “café” matches “cafe”. |
The following example demonstrates configuring initial search by setting these properties.
const searchSettings = {
fields: ['CustomerID'],
operator: 'contains',
key: 'Ha',
ignoreCase: true,
ignoreAccent: true
}This configuration searches the “Customer ID” column for records containing “Ha” (case-insensitive, accent-insensitive). When the grid loads, it automatically filters to show only matching records. If these properties are misconfigured or left “undefined”, the grid displays all records without initial filtering.
import { data } from './datasource';
import { Component, OnInit } from '@angular/core';
import { GridModule, SearchService, SearchSettingsModel, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid [dataSource]='data' [searchSettings]='searchOptions' [toolbar]='toolbarOptions' height='272px'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='Freight' headerText='Freight' textAlign='Right' format='C' width=80></e-column>
<e-column field='OrderDate' headerText='Order Date' textAlign='Right' format='yMd' width=100></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
public searchOptions?: SearchSettingsModel;
ngOnInit(): void {
this.data = data;
this.searchOptions = { fields: ['CustomerID'], operator: 'contains', key: 'Ha', ignoreCase: true, ignoreAccent:true };
this.toolbarOptions = ['Search'];
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));By default, the grid searches all visible columns. Customize this by setting the searchSettings.fields property to limit searching to specific columns only.
Search operators
Search operators are symbols or keywords used to define the type of comparison or condition applied during a search operation. They specify the way the search key is compared with the column data. Different operators enable different types of matching logic. The searchSettings.operator property configures which operator the grid uses.
By default, the searchSettings.operator is set to contains, which returns records containing the search key anywhere in the specified columns. The following operators are available.
| Operator | Description | Example |
|---|---|---|
| startswith | Matches records that begin with the search key | Searching “John” finds “Johnson” and “Johnathan”, but not “St. John” |
| endswith | Matches records that end with the search key | Searching “son” finds “Johnson” and “Allison”, but not “Sunshine” |
| contains | Matches records containing the search key anywhere | Searching “son” finds “Johnson”, “Sunshine”, and “Allison” |
| wildcard | Uses wildcards (* symbol) for pattern matching | Searching “J*n” finds “John”, “Jen”, “Jargon” |
| like | Uses SQL LIKE pattern (% symbol) for matching | Searching “J%n” finds “John”, “Jen”, “Jargon” |
| equal | Matches records exactly equal to the search key | Searching “John” finds only cells containing exactly “John” |
| notequal | Matches records that DO NOT equal the search key | Searching “John” finds all records except those with exactly “John” |
These operators provide flexibility in defining the search behavior and allow different types of comparisons to be performed based on the requirements.
The following example demonstrates setting the searchSettings.operator property based on the selected dropdown value using the change event of the DropDownList component.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChangeEventArgs, DropDownListAllModule } from '@syncfusion/ej2-angular-dropdowns';
import { GridComponent, GridModule, SearchService, SearchSettingsModel, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [ GridModule,DropDownListAllModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `
<div style="display: flex">
<label style="padding: 10px 10px 26px 0">
Change the search operators:
</label>
<ejs-dropdownlist
style="margin-top:5px"
id="value"
#dropdown
index="0"
width="100"
[dataSource]="ddlData"
[fields]='fields'
(change)="valueChange($event)"
></ejs-dropdownlist>
</div>
<ejs-grid #grid style="padding: 5px 5px" [dataSource]='data' [toolbar]='toolbarOptions' [searchSettings]="searchSettings" height='220px'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='ShipName' headerText='Ship Name' width=110></e-column>
<e-column field='ShipCountry' headerText='Ship Country' textAlign='Right' width=100></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
public searchSettings?: SearchSettingsModel
@ViewChild('grid') public grid?: GridComponent;
public fields?: object = { text: 'text', value: 'value' };
public ddlData?: object[] = [
{ text: 'startswith', value: 'startswith' },
{ text: 'endswith', value: 'endswith' },
{ text: 'wildcard', value: 'wildcard' },
{ text: 'like', value: 'like' },
{ text: 'equal', value: 'equal' },
{ text: 'not equal', value: 'notequal' },
];
ngOnInit(): void {
this.data = data;
this.toolbarOptions = ['Search'];
this.searchSettings = { operator: 'contains' };
}
valueChange(args: ChangeEventArgs): void {
(this.grid as GridComponent).searchSettings.operator = args.value as string;
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Search by external button
The Grid component provides the search method, which enables programmatic searching. This allows implementing custom search interfaces outside the grid’s toolbar, such as using a dedicated search button or external search box.
Implementation steps for searching via an external button:
- Add a textbox and a button element outside the grid component.
- Attach a
clickevent handler to the button. - Enter the text to search in the grid.
- In the event handler, get the entered text from the textbox.
- Call the grid’s
searchmethod, passing the text as a parameter.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { GridComponent, GridModule, SearchService, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { TextBoxComponent, TextBoxModule } from '@syncfusion/ej2-angular-inputs';
@Component({
imports: [ GridModule, ButtonModule,TextBoxModule],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `
<div class="e-float-input" style="width: 120px; display: inline-block;">
<ejs-textbox #searchInput width="100" placeholder="Search text"></ejs-textbox>
<span class="e-float-line"></span>
</div>
<button ejs-button id='search' (click)='search()'>Search</button>
<ejs-grid #grid [dataSource]='data' height='260px'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='ShipCity' headerText='Ship City' width=100></e-column>
<e-column field='ShipName' headerText='Ship Name' width=120></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
@ViewChild('grid') public grid?: GridComponent;
@ViewChild('searchInput') public searchInput?: TextBoxComponent;
ngOnInit(): void {
this.data = data;
}
search() {
const searchText: string = (this.searchInput as TextBoxComponent).value;
(this.grid as GridComponent).search(searchText);
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Search specific columns
By default, the search functionality searches across all visible columns. However, scenarios may require searching only specific columns. The searchSettings.fields property enables limiting the search scope to targeted columns.
This approach is useful when:
- Applications work with large grids containing many columns (reduces processing time).
- Search should focus on key columns (like “Customer ID” or “Freight”) rather than all columns.
- Displaying search results for specific fields improves relevance.
The following example searches only the “Customer ID”, “Freight”, and “Ship Country” columns.
import { data } from './datasource';
import { Component, OnInit } from '@angular/core';
import { GridModule, SearchService, SearchSettingsModel, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [ GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid #grid [dataSource]='data' [height]='260' [searchSettings]='searchSettings' [toolbar]='toolbar' >
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='Freight' headerText='Freight' textAlign='Center' format='C2' width=80></e-column>
<e-column field='ShipCity' headerText='Ship City' width=100 ></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public searchSettings?: SearchSettingsModel;
public toolbar?: ToolbarItems[];
ngOnInit(): void {
this.data = data;
this.toolbar = ['Search'];
this.searchSettings = {fields: ['CustomerID', 'Freight', 'ShipCity']};
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Search on each key stroke
The real-time search feature enables searching as each keystroke is entered into the search box. This provides immediate, dynamic search results without requiring pressing Enter or clicking a button.
Implementation of real-time search:
- Bind the
keyupevent to the search input element inside the grid’s created event. - The
keyupevent triggers the search method on each keystroke. - The grid results update in real-time as typing occurs.
In the following example, the created event of the grid binds the keyup event to the search input element. When typing occurs, the keyup event fires, retrieves the current search text from the input, and calls the grid’s search method with the new text. This produces real-time filtering as typing happens.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, GridModule, SearchService, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid #grid [dataSource]='data' [toolbar]='toolbarOptions' (created)='created()' height='273' width='100%'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' width=80></e-column>
<e-column field='ShipCity' headerText='Ship City' width=100></e-column>
<e-column field='ShipCountry' headerText='Ship Country' width=100></e-column>
<e-column field='ShipName' headerText='Ship Name' width=120></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
@ViewChild('grid')
public grid?: GridComponent;
ngOnInit(): void {
this.data = data;
this.toolbarOptions = ['Search'];
}
created(): void {
(document.getElementById((this.grid as GridComponent).element.id + "_searchbar") as Element).addEventListener('keyup', () => {
(this.grid as GridComponent).search(((event as MouseEvent).target as HTMLInputElement).value)
});
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Search on each key stroke approach may affect the performance of the application when dealing with a large number of records.
Perform search based on column formatting
By default, search operations examine the underlying raw data in cells. However, scenarios may require searching based on formatted values visible in the interface. For example, searching for dates in a specific format or currency amounts with formatting applied. This can be achieved using the grid.valueFormatterService.fromView method.
Implementation of searching the formatted data:
- Use the
grid.valueFormatterService.fromViewmethod within the actionBegin event. - This method retrieves the formatted (displayed) value of a cell.
- Compare the formatted value against the search term using
ORlogic. - This allows the grid to match both raw and formatted data.
In the following example, the actionBegin event checks if a column has formatting applied. If it does, the formatted value is retrieved and compared against the search term using OR logic, allowing the grid to match both raw and formatted data. In the actionBegin event, retrieve the search value from the getColumns method. Iterate through the columns and check whether the column has a format specified. If the column has a format specified, use the grid.valueFormatterService.fromView method to get the formatted value of the cell. If the formatted value matches the search value, set the OR predicate that includes the current column filter and the new filter based on the formatted value.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { GridComponent, GridModule, KeyboardEventArgs, SearchEventArgs, SearchService, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { Predicate, Query } from '@syncfusion/ej2-data';
@Component({
imports: [GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid #grid [dataSource]='data' [toolbar]='toolbarOptions' height='272px' (actionBegin)="actionBegin($event)" (keyPressed)="keyPressed($event)">
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='Freight' headerText='Freight' textAlign='Right' format='C' width=80></e-column>
<e-column field='OrderDate' headerText='Order Date' textAlign='Right' format='yMd' width=100></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
@ViewChild('grid') public grid?: GridComponent;
ngOnInit(): void {
this.data = data;
this.toolbarOptions = ['Search'];
}
actionBegin(args:SearchEventArgs) {
if (args.requestType == 'searching') {
args.cancel = true;
setTimeout(() => {
var columns = (this.grid as GridComponent).getColumns();
var predicate = null;
for (var i = 0; i < columns.length; i++) {
var val = (this.grid as GridComponent).valueFormatterService.fromView(
args.searchString as string,
columns[i].getParser(),
columns[i].type
);
if (val) {
if (predicate == null) {
predicate = new Predicate(
columns[i].field,
'contains',
val,
true,
true
);
} else {
predicate = predicate.or(
columns[i].field,
'contains',
val,
true,
true
);
}
}
}
(this.grid as GridComponent).query = new Query().where(predicate as Predicate);
}, 200);
}
}
keyPressed(args: KeyboardEventArgs) {
if (
args.key == 'Enter' &&
args.target instanceof HTMLElement &&
args.target.closest('.e-search') &&
(args.target as HTMLInputElement).value == ''
) {
args.cancel = true;
(this.grid as GridComponent).query = new Query();
}
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Perform search operation in Grid using multiple keywords
The Grid component supports searching with multiple keywords simultaneously. This enables narrowing search results by matching multiple conditions at once. For example, finding records where CustomerID contains “A” and ShipCountry contains “US”.
Implementation of multi-keyword search:
- Use the actionBegin event.
- Split the search text by a delimiter (comma, space, etc.).
- Create filter predicates for each keyword.
- Combine them using
ORlogic (records matching any keyword are shown).
In the following example, entering “France, Germany” in the search box searches for records where the country is either “France” or “Germany”. Each keyword is then utilized to create a predicate that checks for a match in the desired columns. If multiple keywords are present, the predicates are combined using an OR condition. Finally, the grid’s query property is updated with the constructed predicate, and the Grid is refreshed to update the changes in the UI.
On the other hand, the actionComplete event is used to manage the completion of the search operation. It ensures that the search input value is updated if necessary and clears the query when the search input is empty.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Column, GridComponent, GridModule, SearchEventArgs, SearchService, SearchSettingsModel, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { Predicate, Query } from '@syncfusion/ej2-data';
@Component({
imports: [GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid #Grid [dataSource]='data' [toolbar]='toolbarOptions' [searchSettings]='searchOptions'(actionBegin)="actionBegin($event)" (actionComplete)="actionComplete($event)" height='273' width='100%'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' width=80></e-column>
<e-column field='ShipCity' headerText='Ship City' width=100></e-column>
<e-column field='ShipCountry' headerText='Ship Country' width=100></e-column>
<e-column field='ShipName' headerText='Ship Name' width=120></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public values?: string;
public key = '';
public removeQuery = false;
public valueAssign = false;
public data?: object[];
public toolbarOptions?: ToolbarItems[];
public searchOptions?: SearchSettingsModel;
@ViewChild('Grid') public grid?: GridComponent;
ngOnInit(): void {
this.data = data;
this.searchOptions = {
fields: [
'OrderID',
'CustomerID',
'EmployeeID',
'ShipCity',
'ShipCountry',
'ShipName'
],
operator: 'contains',
key: '',
ignoreCase: true,
};
this.toolbarOptions = ['Search'];
}
actionBegin({ requestType, searchString }: SearchEventArgs) {
if (requestType == 'searching') {
const keys = (searchString as string).split(',');
var flag = true;
var predicate: any;
if (keys.length > 1) {
if ((this.grid as GridComponent).searchSettings.key !== '') {
this.values = searchString;
keys.forEach((key: string) => {
(this.grid as GridComponent).getColumns().forEach((col: Column) => {
if (flag) {
predicate = new Predicate(col.field, 'contains', key, true);
flag = false;
}
else {
var predic = new Predicate(col.field, 'contains', key, true);
predicate = predicate.or(predic);
}
});
});
(this.grid as GridComponent).query = new Query().where(predicate);
(this.grid as GridComponent).searchSettings.key = '';
this.valueAssign = true;
this.removeQuery = true;
(this.grid as GridComponent).refresh();
}
}
}
}
actionComplete(args: SearchEventArgs) {
if (args.requestType === 'refresh' && this.valueAssign) {
const searchBar = document.querySelector<HTMLInputElement>('#' + (this.grid as GridComponent).element.id + '_searchbar');
if (searchBar) {
searchBar.value = this.values || '';
this.valueAssign = false;
}
else if (
args.requestType === 'refresh' &&
this.removeQuery
) {
const searchBar = document.querySelector<HTMLInputElement>('#' + (this.grid as GridComponent).element.id + '_searchbar');
if (searchBar) {
searchBar.value = '';
}
(this.grid as GridComponent).query = new Query();
this.removeQuery = false;
(this.grid as GridComponent).refresh();
}
}
(
document.getElementById((this.grid as GridComponent).element.id + '_searchbar') as Element).addEventListener('keyup', (args) => {
if ((args.target as HTMLInputElement).value === '' && ((args as KeyboardEvent).key === 'Enter' || (args as KeyboardEvent).key === 'Backspace')) {
(this.grid as GridComponent).query = new Query();
this.removeQuery = false;
(this.grid as GridComponent).refresh();
}
});
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));By using multiple keywords, searches are more flexible and powerful. Keywords are split by a delimiter and combined using
ORlogic, meaning the grid displays records matching any of the provided keywords.
Ignoring accents while searching
By default, the search operation distinguishes between characters with and without accents (diacritics). For example, searching for “Chai” does not find “Chäi”. Set the searchSettings.ignoreAccent property to true to make the search accent-insensitive.
This feature is useful when:
- Applications work with international data containing accented characters (é, ñ, ü, etc.).
- Search should match both “Chäi” and “Chai” as equivalent.
- Input searches may not include accents even though data contains them.
The following example demonstrates toggling the ignoreAccent property using a switch button. Additionally, the EJ2 Toggle Switch Button component is included to modify the value of the searchSettings.ignoreAccent property. When the switch is toggled, the change event is triggered, and the searchSettings.ignoreAccent property is updated accordingly. This functionality helps to visualize the impact of the searchSettings.ignoreAccent setting when performing search operations.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ChangeEventArgs, ButtonModule, CheckBoxModule, RadioButtonModule, SwitchModule, } from '@syncfusion/ej2-angular-buttons';
import { GridComponent, GridModule, SearchService, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [
GridModule,
ButtonModule,
CheckBoxModule,
RadioButtonModule,
SwitchModule,
],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `
<div>
<label style="padding: 10px 10px">
Enable or disable ignoreAccent property
</label>
<ejs-switch id="switch" (change)="onSwitchChange($event)"></ejs-switch>
</div>
<ejs-grid #grid [dataSource]='data' [toolbar]='toolbarOptions' height='272px'>
<e-columns>
<e-column field='CategoryName' headerText='Category Name' width='100'></e-column>
<e-column field='ProductName' headerText='Product Name' width='130'></e-column>
<e-column field='QuantityPerUnit' headerText='Quantity per unit' width='150' textAlign='Right'></e-column>
<e-column field='UnitsInStock' headerText='Units In Stock' width='80' textAlign='Right'></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
@ViewChild('grid')
public grid?: GridComponent;
ngOnInit(): void {
this.data = data;
this.toolbarOptions = ['Search'];
}
onSwitchChange(args: ChangeEventArgs) {
if (args.checked) {
(this.grid as GridComponent).searchSettings.ignoreAccent = true;
} else {
(this.grid as GridComponent).searchSettings.ignoreAccent = false;
}
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));
- The
ignoreAccentproperty can be combined with other search settings such asfields,operator,ignoreCaseto customize search behavior.- This feature applies only to non-ASCII characters (characters with diacritical marks).
- Enabling accent-ignoring may have a slight performance impact on very large datasets.
Highlight the search text
Search text highlighting visually emphasizes where search keywords appear in the grid. The Grid component supports highlighting matched text by styling the text with colors or background colors.
Implementation approach:
- Use the queryCellInfo event.
- This event fires for each cell during rendering.
- Check if the current cell’s column is the search column.
- Retrieve the cell value and search keyword.
- Replace the matched text with the same text wrapped in a
<span>element with a “customcss” class.
Define the CSS class to apply highlighting styles (e.g., background-color: yellow;):
.customcss {
background-color: yellow;
font-weight: bold;
}import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Column, GridComponent, GridModule, QueryCellInfoEventArgs, SearchEventArgs, SearchService, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
interface ColumnData{
[key: string]: number| string;
OrderID:number,
Freight:number,
CustomerID:string,
ShipCity:string,
ShipName:string,
ShipCountry:string,
ShipPostalCode:number
}
@Component({
imports: [ GridModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template: `<ejs-grid #grid [dataSource]='data' [toolbar]='toolbarOptions' (actionBegin)="actionBegin($event)" (queryCellInfo)="queryCellInfo($event)" height='273' width='100%'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='EmployeeID' headerText='Employee ID' textAlign='Right' width=80></e-column>
<e-column field='ShipCity' headerText='Ship City' width=100></e-column>
<e-column field='ShipCountry' headerText='Ship Country' width=100></e-column>
<e-column field='ShipName' headerText='Ship Name' width=120></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public key?:string = '';
public data?: object[];
public toolbarOptions?: ToolbarItems[];
@ViewChild('grid') public grid?: GridComponent;
ngOnInit(): void {
this.data = data;
this.toolbarOptions = ['Search'];
}
actionBegin(args:SearchEventArgs) {
if (args.requestType === 'searching') {
(this.key as string) = (args.searchString as string).toLowerCase();
}
}
queryCellInfo(args: QueryCellInfoEventArgs) {
const key = (this.key as string) ?? '';
if (!key) return;
const cellEl = args.cell as HTMLElement | null | undefined;
if (!cellEl) return;
const col = args.column as Column;
const data = args.data as Record<string, unknown>;
const cellContent = (data?.[col.field] ?? '') as string;
if (!cellContent) return;
const baseText = cellEl.innerText ?? '';
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const highlighted = baseText.replace(
new RegExp(escapedKey, 'gi'),
(match) => `<span class="customcss">${match}</span>`
);
cellEl.innerHTML = highlighted;
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Clear search by external button
The Grid component provides the capability to clear search results and reset the grid to display all records. This is useful for resetting search filters when a “Clear” or “Reset” button is clicked.
Implementation of clearing search results from an external button:
- Set the searchSettings.key property to an empty string.
- This property represents the current search text.
- Setting it to empty clears the search text and resets the grid.
The following example demonstrates clearing search records using an external button.
import { data } from './datasource';
import { Component, OnInit, ViewChild } from '@angular/core';
import { ButtonModule } from '@syncfusion/ej2-angular-buttons';
import { GridComponent, GridModule, SearchService, SearchSettingsModel, ToolbarItems, ToolbarService } from '@syncfusion/ej2-angular-grids';
@Component({
imports: [ GridModule, ButtonModule ],
providers: [SearchService, ToolbarService],
standalone: true,
selector: 'app-root',
template:
`<button ejs-button id='clear' (click)='clearSearch()'>Clear Search</button>
<ejs-grid #grid style="margin-top:5px" [dataSource]='data' [searchSettings]='searchOptions' [toolbar]='toolbarOptions' height='260px'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column>
<e-column field='CustomerID' headerText='Customer ID' width=100></e-column>
<e-column field='ShipCity' headerText='Ship City' width=100></e-column>
<e-column field='ShipName' headerText='Ship Name' width=120></e-column>
</e-columns>
</ejs-grid>`
})
export class AppComponent implements OnInit {
public data?: object[];
public toolbarOptions?: ToolbarItems[];
public searchOptions?: SearchSettingsModel;
@ViewChild('grid') public grid?: GridComponent;
ngOnInit(): void {
this.data = data;
this.searchOptions = { fields: ['CustomerID'], operator: 'contains', key: 'Ha', ignoreCase: true };
this.toolbarOptions = ['Search'];
}
clearSearch() {
(this.grid as GridComponent).searchSettings.key = '';
}
}import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Alternatively, the search box’s built-in clear icon also clears search results. When the search box has focus or contains text, clicking the clear icon removes the text and resets the grid to display all records.
Retrieving searched records using a button click
The Grid component enables retrieving the records that match the current search criteria. This allows capturing searched results for export, further processing, or display in another component.
Implementation of retrieving searched records using an external button.
- Use the actionComplete event.
- This event fires when a search action completes.
- Access the search text from the event.
- Use the
DataManager.executeQuery()method with the search text to retrieve matching records.
The following example demonstrates to retrieve searched records using an external button.
import { data } from './datasource';
import { Component, OnInit } from '@angular/core';
import { GridModule, PageService, ToolbarService } from '@syncfusion/ej2-angular-grids';
import { DataManager, Query } from '@syncfusion/ej2-data';
@Component({
imports: [GridModule],
providers: [PageService, ToolbarService],
standalone: true,
selector: 'app-root',
templateUrl: 'app.template.html'
})
export class AppComponent implements OnInit {
public data?: Object[];
public pageSettings?: Object;
public toolbar?: string[];
public lastSearchString: string = '';
ngOnInit(): void {
this.data = data;
this.pageSettings = { pageCount: 5 };
this.toolbar = ['Search'];
}
public actionComplete(args: any): void {
if (args.requestType === 'searching') {
this.lastSearchString = args.searchString; // Store the last searched value.
}
}
public getSearchedRecords(): void {
if (this.lastSearchString) {
const clonedData = JSON.parse(JSON.stringify(this.data)); // Clone data to avoid modifying original.
new DataManager(clonedData).executeQuery( new Query().search(this.lastSearchString, [], undefined, true)).then((e: any) => {
console.log('Searched Records:', e.result); // Log searched records.
});
}
}
}<button id="getSearchedRecords" (click)="getSearchedRecords()">Get Searched Records</button>
<ejs-grid [dataSource]='data' allowPaging='true' [pageSettings]='pageSettings' [toolbar]='toolbar' (actionComplete)='actionComplete($event)'>
<e-columns>
<e-column field='OrderID' headerText='Order ID' width='120' textAlign='Right' isPrimaryKey='true' ></e-column>
<e-column field='CustomerID' headerText='Customer ID' width='150' ></e-column>
<e-column field='Freight' headerText='Freight' width='120' format='C2' ></e-column>
<e-column field='ShipCountry' headerText='Ship Country' width='150' ></e-column>
</e-columns>
</ejs-grid>import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));See also
How to perform search by using Wildcard and LIKE operator filter