Introduction
We will see how to implement a highlight pipe in Angular. This highlight pipe will highlight on the basis of the search term passed as an argument to this pipe. We will create a custom pipe for this use case.
- We should know about the @Pipe decorator. The pipe decorator allows us to specify a pipe name which we will reference in our HTML template to use that particular pipe.
- To specify a custom pipe, we need to import a @Pipe decorator.
- We can give any value to the custom pipe. It can be an array, string, object, etc.
Create a pipe using the Angular CLI command
ng generate pipe highlight
Now we will go to the highlight.pipe.ts file and write the below code:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "highlight",
})
export class HighlightPipe implements PipeTransform {
transform(value: string, searchTerm: string): string {
if (!value || !searchTerm) return value;
const startIndex: number = value.toLowerCase().indexOf(searchTerm.toLowerCase());
if (startIndex === -1) return value;
const endIndex: number = startIndex + searchTerm.length;
const textBeforeHighlight: string = value.substring(0, startIndex);
const highlightedText: string = value.substring(startIndex, endIndex);
const textAfterHighlight: string = value.substring(endIndex);
return `${textBeforeHighlight}${highlightedText}${textAfterHighlight}`;
}
}
Call this pipe in your HTML file
<div *ngFor="let item of list | search: searchTerm">
<p[innerHTML]="item.name | highlight: searchTerm"></p>
</div>
Comments
Post a Comment