[Fixed] Setting a different color only for words which came out of dropdown in textarea editor(angular)


What I did:

I have a dropdown. I also have a textarea. I enter text in textarea and I also choose words from the dropdown and add it to the textarea. I have done this part.


Now I wanna differentiate the words which came from the dropdown. So I wanna show those particular words alone in red color. Any word entered through dropdown or any word entered by hand which is same as any one of the dropdown value should be shown in red color. This is what I am trying to do . I have searched stackoverflow but I could find any solutions. Kindly help if you guys know



<textarea #text [(ngModel)]='textValue' rows="10" cols="70">
  <mat-form-field class="input-style">

    <mat-select (change)="changeValue($event)">
      <mat-option *ngFor="let li of list4" [value]="li">

My TS:

  changeValue(ev) {
        this.textValue += ` ${ev.value}`;

I have attached my stackblitz link:


Update 04-04-2021 please take a look to Owen Kevin’s answer in this SO because my code don’t take account the "scroll"

the only way to "highlight" text inside a textarea is to have two layers, one with a text area and another one with a div with [innerHtml]

the problem with a textarea is that you need use the same font-family than the div

from this codePen the .html like

<div class="container" [style.width]="text.getBoundingClientRect().width+'px'"
  <div class="backdrop">
    <div class="highlights" [innerHtml]="textFormatted"></div>
  <textarea #text [ngModel]='textValue' (ngModelChange)="change($event)" rows="10" cols="40">

A function "formatted"

    return message.replace(/\n/g, "<br />").replace(this.regExpr,"<mark>$&</mark>")

replace the message with the "mark" in the words selecteds

  regExpr=new RegExp(this.list4.map(x=>'('+x+')').join('|'),"g");

Remember call to this.formatted each time you change the textarea

  changeValue(ev) {
    this.textValue += ` ${ev.value}`;
    this.textValue = message;


And, behare! the .css to change the mark should be in the styles.css

The stackblitz

Update if we want to change into italic is that we need made transparent the text-area color and colored the "hightlight". This make "loose" the cursor.

.highlights {
    color: #444;
textarea {
  color: transparent;

We can use -webkit-text-fill-color but it’s not a standards css (works on FireFox, Chrome and Edge)

@supports (-webkit-text-stroke: 1px black) {
  textarea {
    -webkit-text-stroke: 1px transparent;
    -webkit-text-fill-color: transparent;

The modiffied stackblitz

Leave a Reply

(*) Required, Your email will not be published