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 ?

My HTML

<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);
  this.renderer.setStyle(a,'font-weight','bold');
  }
}

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

1 Answers

2
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>`));
   }

https://stackblitz.com/edit/renderer2-example-2-yweqw1?file=src/app/app.component.ts