如何突出显示内容可编辑div中的文本?

时间:2018-12-29 16:01:03

标签: angular form-control

我有contenteditable div格式,并希望当我在其中键入超过特定数量的字符(超过200个字符)时,此后的所有文本都突出显示。

这是我的html代码:

 <div contenteditable="true"
       class="text-box"
       #textarea
       (input)="change($event);touch($event)"
       (keyup)="postLengthCheck('text')"
       maxlength="2300">
  </div>

这是我的打字稿代码:

export const EPANDED_TEXTAREA_VALUE_ACCESSOR: any = {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InstagramContentProductionComponent),
      multi: true,
    };
@Component({
      selector: 'app-instagram-content-production',
      templateUrl: './instagram-content-production.component.html',
      styleUrls: ['./instagram-content-production.component.scss'],
      providers: [EPANDED_TEXTAREA_VALUE_ACCESSOR],
    })

export class InstagramContentProductionComponent implements OnInit, ControlValueAccessor {

      public postLength: any;
      public validTextLength: any;
      createPostForm: FormGroup;
      @ViewChild('boxPosition') public boxPosition: ElementRef;
      innerWidth: any;
      x: any;
      match: any;
      markText: any;
      replaced: any;
      @ViewChild('textarea') textarea;
      onChange;
      onTouched;

      constructor(public appGlobal: AppGlobals, private router: Router, private renderer: Renderer2) {
        this.mySwitch = false;
      }

      writeValue(value: any): void {
        const div = this.textarea.nativeElement;
        this.renderer.setProperty(div, 'textContent', value);
      }

      registerOnChange(fn: any): void {
        this.onChange = fn;
      }

      registerOnTouched(fn: any): void {
        this.onTouched = fn;
      }

      change($event) {
        // Angular does not know that the value has changed.
        // from our component, so we need to update her with the new value.
        console.log($event);
        this.registerOnChange($event.target.textContent);
      }

      touch($event) {
        this.registerOnTouched($event.target.textContent);
      }

postLengthCheck(input) {
    if (input === 'text') {
      this.postLength = this.onChange.length;
      this.validTextLength = 200 - this.postLength;
      if (this.postLength > 200) {
        this.x = this.onChange.substring(200, this.postLength);
        // console.log(this.x);
        this.match = new RegExp(this.x, 'ig');
        this.markText = '<span class="highlighted-text">' + this.x + '<\/span>';
        this.onChange = this.onChange.replace(this.match, this.markText);
        console.log(this.onChange);
      }
    }
  }

 ngOnInit() {
    }
}

在我的css中,我定义了highlighted-text类,如下所示:

.highlighted-text {
  border-radius: 3px;
  color: transparent;
  background-color: #b1d5e5;
}

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

0 个答案:

没有答案