A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the h
One difficulty the innerHTML method has is in styling the tag. Another method is to place this in a component, allowing for much more options in styling.
highlighted-text.component.html
{{matched}}{{unmatched}}
highlighted-text.component.ts
import { Component, Input, OnChanges, OnInit } from "@angular/core";
@Component({
selector: "highlighted-text",
templateUrl: "./highlighted-text.component.html",
styleUrls: ["./highlighted-text.component.css"]
})
export class HighlightedTextComponent implements OnChanges {
@Input() needle: String;
@Input() haystack: String;
public matched;
public unmatched;
ngOnChanges(changes) {
this.match();
}
match() {
this.matched = undefined;
this.unmatched = this.haystack;
if (this.needle && this.haystack) {
const needle = String(this.needle);
const haystack = String(this.haystack);
const startIndex = haystack.toLowerCase().indexOf(needle.toLowerCase());
if (startIndex !== -1) {
const endLength = needle.length;
this.matched = haystack.substr(startIndex, endLength);
this.unmatched = haystack.substr(needle.length);
}
}
}
}
highlighted-text.component.css
mark {
display: inline;
margin: 0;
padding: 0;
font-weight: 600;
}
Usage