0

Below is my directive for trying to highlight a keyword in a matInput.

import {Directive, Renderer2, OnInit, ElementRef} from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

@Directive({
  selector: '[appKeywordHighlight]'
})
export class KeywordHighlightDirective implements OnInit {

  constructor(private renderer: Renderer2,
              private elRef: ElementRef,
              private _sanitizer:DomSanitizer) { }

  ngOnInit() {
    console.log(this.elRef.nativeElement.value)
    this.renderer.setProperty(this.elRef.nativeElement,'value', "I am <span>very</span> happy");
  }

} //end class

In my input box this is what I get:

I am <span>very</span> happy

If not possible then ok but if possible then how do I highlight keywords? I will assing a class to the span to color.

<mat-form-field>
     <mat-label>keyword:</mat-label>
        <input matInput formControlName="keyword" appKeywordHighlight>
</mat-form-field>
Tampa
  • 75,446
  • 119
  • 278
  • 425
  • Did you try to use an inline css inside de span to highlight it? – Vítor França Nov 27 '21 at 13:13
  • Is there an example? Dont know what a de span is – Tampa Nov 27 '21 at 13:16
  • If you only want to highlight use the [Mark Tag](https://www.w3schools.com/tags/tag_mark.asp) which is better, and also try to apply the inline CSS like: this.renderer.setProperty(this.elRef.nativeElement,'value', "I am very happy"); – Vítor França Nov 27 '21 at 13:39
  • Thanks but now shows this in the input box test I am very happy – Tampa Nov 27 '21 at 13:53
  • Take a look at [this](https://blog.sreyaj.dev/highlight-text-in-angular-using-directives) example of directive, it uses a hostBiding with innerHtml, maybe this way you will be able to inject HTML inside of your div instead of inject the plain text – Vítor França Nov 27 '21 at 13:56
  • Tried does not work with input. Starting to think its not possible. – Tampa Nov 27 '21 at 15:02
  • Maybe if you input that marker inside the input [value field](https://stackoverflow.com/questions/5823835/html-in-the-input-field-value), instead of trying to inject the HTML. – Vítor França Nov 27 '21 at 15:13

0 Answers0