I wanted to highlight a specific word in a string. For Example Hello Welcome! Click here for more details in this string I wanted to highlight Hello Welcome .

Point to be noted : Highlight text is dynamic, it keeps changing.

So How to find the highlightText and apply styles to it using angular renderer ?

Please suggested other possible solutions ?


<p #test>Hello Welcome! Click here for more details</p>

My code

Below code dosen't work .

export class AppComponent implements AfterViewInit {
  @ViewChild('test') test: ElementRef;

  higlightText= 'Hello Welcome';

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
  let text = this.test.nativeElement.innerHTML;
  let a = text.search(this.higlightText);

Link to Project: https://stackblitz.com/edit/renderer2-example-2-vtbhfq?file=src%2Fapp%2Fapp.component.ts

1 Answers

Royi Namir On

Continuing what you've started : change ngAfterViewInit to :

  ngAfterViewInit() {
     this.renderer.setProperty(this.test.nativeElement, 'innerHTML', this.test.nativeElement.innerHTML.replace(this.higlightText,`<b>${this.higlightText}</b>`));