【问题标题】:how to highlight text in textarea in angular?如何以角度突出显示文本区域中的文本?
【发布时间】:2019-05-26 21:58:34
【问题描述】:

我有 textarea 表单,当我在其中输入超过特定数量的字符(超过 2200 个字符)时,我希望在此之后的所有文本都会突出显示。

这是我的 html 代码:

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

这是我的打字稿代码:

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;
        }
      }
    }
}

在我的css 中,我定义mark 类如下:

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

但这不起作用。我该如何解决这个问题?

【问题讨论】:

    标签: angular textarea form-control


    【解决方案1】:

    我建议您不要创建自己的 HTML 标签,而是使用 &lt;span class="highlighted-text"&gt;the text&lt;/span&gt; 之类的标签。

    另外,textarea 仅包含文本(不是 HTML),因此您必须将其更改为 &lt;div contenteditable="true"&gt;the text&lt;/div&gt;,这就是每个 HTML 所见即所得编辑器的工作方式。

    【讨论】:

    • 如何使用 div 设置表单控件??
    • 我建议你通过实现ControlValueAccessor来创建自己的表单控件。事实上,Angular 并没有为它提供一个实现,因为它太固执己见了。
    • 我怎样才能用 ControlValueAccessor 做到这一点?
    • 将你的div contenteditable="true"嵌入到一个组件中,然后让你的组件实现ControlValueAccessor,然后编写函数的实现。之后,您将能够将该组件用作表单控件。
    • 嗯,它应该和你之前做的没什么不同,现在很抱歉,如果你在这一点上遇到麻烦,你应该打开一个新问题,因为你的原始问题已经得到了回答.如果您这样做,我很乐意再次为您提供帮助。
    猜你喜欢
    • 2022-01-06
    • 2022-01-23
    • 2010-09-13
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    相关资源
    最近更新 更多