Angular 2 - Highlight text of a DIV as user types characters in an input field

I am trying to give to my users some feedback on my angular 2 application by highlighting text from a div as they type in an input.

This would be the perfect solution:

Highlight text of a DIV as user types characters in an input field

However, with the Angular2's different approach for DOM Manipulation I haven't been able to do it, any suggestions?

Upvotes: 3

Views: 1164

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657781

<div [innerHTML]="highlighted"></div>
<input [(ngModel)]="text" (ngModelChange)="updateHighlight()" name="high">
class MyComponent {
  this.allText = 'lorem ipsum ...';
  text = '';
  highlighted = '';
  updateHighlight() {
    this.highlighted = this.text
        ? allText.replace(new RegExp('('+this.text+')','ig'), 
            '<span class=highlight>$1</span>')
        : allText;        
  }
}

Upvotes: 3

Related Questions