mm1975
mm1975

Reputation: 1655

Angular Typescript replace string innerHTML with span

I'm searching for a string in the innerHTML of a div and want to set a span. My approach doesn't work without any error. What's going wrong?

HTML

<div class="resultText" #txt></div>

JS

...
@ViewChild('txt') txt: ElementRef;
...
this.txt.nativeElement.innerHTML = text;
...
var query = 'test';
this.highlight(query);

highlight(query) {
      var c = this.txt.nativeElement.innerHTML;
      c.replace(new RegExp(query, "gi"), match => {
          console.log('query: ' + query);
          return '<span class="highlightText">' + match + '</span>';
      });
}

Upvotes: 0

Views: 2982

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You are not assigning the replaced text back to innerHTML

this.txt.nativeElement.innerHTML = c.replace(new RegExp(query, "gi"), match => {
      console.log('query: ' + query);
      return '<span class="highlightText">' + match + '</span>';
});

Upvotes: 1

Related Questions