Mohandes
Mohandes

Reputation: 291

how to highlight text in textarea in angular?

i have textarea form and want when i type more than specific number of character in it (more than 2200 character), all text after this get highlighted.

this is my html code:

<div class="form-group">
          <textarea type="text"
                    id="textAreaScroll"
                    formControlName="text"
                    placeholder="متن ..."
                    (keyup)="postLengthCheck('text')">
          </textarea>
</div>

and this is my typescript code:

postLengthCheck(input) {
    if (input === 'text') {
      if (this.createPostForm.controls['text'].value !== null) {
        this.postLength = this.createPostForm.controls['text'].value.length;
        this.validTextLength = 2200 - this.postLength;
        if (this.postLength > 2200) {
          this.x = this.createPostForm.controls['text'].value.substring(2200, this.postLength);
          console.log(this.x);
          this.match = new RegExp(this.x, 'ig');
          this.markText = '<mark>' + this.x + '<\/mark>';
          this.replaced = this.createPostForm.controls['text'].value.replace(this.match, this.markText);
          this.createPostForm.controls['text'].value = this.replaced;
        }
      }
    }
}

and in my css i define mark class like below:

mark {
  border-radius: 3px;
  color: transparent;
  background-color: #b1d5e5;
}

but this not worked. how can i fix this problem?

Upvotes: 1

Views: 4318

Answers (1)

Guerric P
Guerric P

Reputation: 31825

I suggest you do not create your own HTML tags, use something like <span class="highlighted-text">the text</span> instead.

Also, a textarea only contains text (not HTML) so you have to change it to a <div contenteditable="true">the text</div>, that's how every HTML WYSIWYG editor works.

Upvotes: 2

Related Questions