Reputation: 862
I built a search component to search for names in a list.
List that is grouped by date.
When I enter the search field I would like the items in the list to highlight if they match with the search.
I could do it in a pipe but when I postpone the code in a component the highlighting does not work anymore.
Pipe : https://stackblitz.com/edit/angular-searchpipe-bmzzez
Component: https://stackblitz.com/edit/highlihgt
I use DomSanitizer to display the text in the html, but it does not work.
I do not know if DomSanitizer is the best solution.
The function of the component that should display the highlight :
handleChange($event: string) {
function filter(messageArray, value) {
function subFind( array, [key, ...keys]) {
return keys.length
? array
.map(o => {
const temp = subFind(o[key], [keys]);
return temp.length && Object.assign({}, o, { [key]: temp });
})
.filter(Boolean)
: array.filter(o => o[key].toLowerCase().includes(value.toLowerCase()));
}
return subFind(messageArray, ['value', 'name']);
}
this.filteredList = this.filteredList.map(item =>
({
...item,
name: this._sanitizer.bypassSecurityTrustHtml(
item.value.forEach(el => {
el.name.replace($event, `<span style='font-weight:bolder'>${$event}</span>`);
})
)
})
);
this.filteredList = filter(this.targetData, $event);
}
the html :
<search-message (searchChanged)="handleChange($event)"></search-message>
<ul>
<div *ngFor="let player of filteredList"> Team : {{player.key}}
<li *ngFor="let eachplayer of player.value">
<span [innerHTML]="eachplayer.name"></span>
</li>
</div>
</ul>
Upvotes: 0
Views: 919