How to filter the data with a common search bar at the top (Angular 8)

Hey there,

Lets say we have common search bar at the top of our application . We need to filter the available data on the main component according to the keywords typed.
We can make use of
- Array filter method
- Component interaction (Child to Parent)
<input matInput type="text" [(ngModel)]="searchword" (input)="searchThis()" />
We use
- ngModel for two way data binding
- [(input)] (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event) logs the value whenever you change the value of the element.
Header Component (header.ts)
import { Component,Input, OnInit, Output,EventEmitter } from '@angular/core';
@Output() searchcriteria = new EventEmitter<String>();
searchThis() {
this.searchcriteria.emit(this.searchword)
}
We create a new event emitter in order to emit the value from the header component to body component. searchThis function will trigger the event for every keypress in the search input field.
Let's see our parent component or body component
Parent component (html)
<app-header (searchcriteria)="searchThis($event)"></app-header>
We use event binding to pass the data from header to parent .
Parent Component (ts)
newArray
searchThis(data) {
this.content = this.newArray
if (data) {
this.content = this.content.filter(function (ele, i, array) {
let arrayelement = ele.name.toLowerCase()
return arrayelement.includes(data)
})
}
else {
console.log(this.content)
}
}
}
newArray is the array contains the data for the component. We assign the data to another array content each time function calls and filter from that array. The filter function changes the existing original array.
The filtered array will be used when we call the function if we change the original array. We need fresh array with full data each time when the function calls.
Let me know how you can improve this.
Until next time,

More in Angular Journey
- ⭐Angular 14 Features ⭐
- ⭐Angular 13 Features ⭐
- 🤷♂️ How to build and deploy angular application to surge using github actions
- Angular 11 Now Available
- Generate QR code with Share / Download Feature ( Angular 8)
- Angular 10 Now Available
- Angular 12 features
- Angular : Dark Fate
- Angular 9 New Features (Finally IVY is here)

Sandeep B
Frontend engineer writing about Angular, JavaScript, and the occasional deep dive into whatever's currently breaking my build.