I have a search input that highlights characters within a paragraph if the search input matches any part of the value:
Search Input:
<h4>Keyword Search</h4>
<mat-form-field appearance="outline" class="mat-form-field">
<mat-label>Search</mat-label>
<input matInput placeholder="Search Text" [(ngModel)]="searchTerm">
</mat-form-field>
//Area to search:
<p [innerHTML]="paragraphText | highlight: searchTerm"></p>
Component file:
searchTerm: string;
paragraphText = "1. Local currency (Kwanza-AOA): up to AOA 50,000.- for residents and non-residents.<br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />2. Foreign currencies:<br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />a. Residents (older than 17 years): up to USD 15,000.- or equivalent;<br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />b. Residents (younger than 18 years): up to USD 5,000.- or equivalent;<br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />c. Non Residents (older than 17 years): up to USD 10,000.- or equivalent;<br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />d. Non Residents (younger than 18 years): up to USD 3,000.- or equivalent. <br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />Exempt: <br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />- If holding a letter (certified by B.N.A./D.O.I.) from a company or entity which took care of payment of all expenses during stay in Angola: foreign currencies up to the amount imported.<br xmlns="http://www.opentravel.org/OTA/2003/05/beta" />- Amounts left with receipts of bills paid or money exchange vouchers. "
Highlight pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightPipe implements PipeTransform {
transform(value: string, searchTerm: string, index= -1 ): any {
if (searchTerm && value) {
value = String(value);
console.log(value);
const startIndex = value.toLowerCase().indexOf(searchTerm.toLowerCase(),index);
if (startIndex != -1) {
const endLength = searchTerm.length;
const matchingString = value.substr(startIndex, endLength);
return value.substring(0,startIndex)+"<mark>" + matchingString + "</mark>"+value.substring(startIndex+endLength);
}
}
return value;
}
}
Current Behavior When typing a letter (ex:'c') into the search field, not all of the 'c's get highlighted. I noticed a pattern that anything after the inline html tags (in the paragraphText property) does not get picked up.
Expected Behavior All characters in the paragraph should be highlighted that match the string in the search field.
What am I doing wrong in the highlight pipe to ensure all values are highlighted??