Search code examples
htmlangularng-bootstraptypeaheadrichtext

Is there an alternative to ngb-highlight for HTML/Rich Text in Angular?


I'm transitioning an app to use html/rich-text instead of just plain, and would like to keep the ease-of-use that something like ngb-highlight provides.

I'm able to search/filter the text myself manually, but would like to keep the typeahead highlighting/search functionality the ngb-highlight element has. Unfortunately the only way I've found to display the html in the element is to use the [innerHTML] attribute, but that overrides [result]-[term] relationship of ngb-highlight.

I've yet to find a solid alternative and would like to put this question out there before committing to just building the solution myself.


Solution

  • I solved this problem and figured I'd help anyone with similar issues:

    The easiest solutions I found were to build your own angular directive and implement it, like so:

    <label [customDirective]="searchText" innerHTML="myRichText"></label>
    

    or to build a custom pipe and implement it, like so:

    <label innerHTML=" myRichText | customPipe: searchText"></label>
    

    I ended up using the pipe method because it was a simpler implementation, however my pipe only does 2 things (add bolding to the html, and react live to changes to the searchText). If you wanted to add more features I'd suggest looking further into building custom angular directives.

    ALSO: Using a pipe has the added benefit of allowing you push your data through a DOMsanitizer on return if you want, letting you get past angular's built-in sanitation protocols. But do this at your own risk since it introduces an avenue for XSS attacks if you don't have full control over the richText/html going through the pipe.