1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import { Directive, Input, ElementRef, AfterViewInit } from "@angular/core";
@Directive({ selector: "[appHighlight]", }) export class HighlightDirective implements AfterViewInit { @Input() highlightText: string = ""; @Input() highlightColor: string = "red";
constructor(private element: ElementRef) {}
ngAfterViewInit(): void { this.highlightAction(); }
private highlightAction() { const innerHTML = this.element.nativeElement.innerHTML; if (!this.highlightText || !innerHTML) { return; } const escapedHighlightText = this.escapeRegExp(this.highlightText); const regex = new RegExp(`${escapedHighlightText}`, "gi"); const highlightedText = innerHTML.replace( regex, (match) => `<span style="color:${this.highlightColor}">${match}</span>` ); this.element.nativeElement.innerHTML = highlightedText; }
private escapeRegExp(text: string): string { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } }
|