在插入符位置插入文本Contenteditable:Angular 8

时间:2020-08-29 18:29:31

标签: javascript angular

我有一个内容可编辑的div,当我尝试在该div中粘贴一些文本时,它总是最后粘贴。我正在使用view child来访问contenteditable div的引用,并使用内部文本来获取值。

问题:如何将复制的文本粘贴到当前光标位置。

请在下面找到我的代码。

Component.html

<div class="text-block" contenteditable #textBlockElement (input)="textOnChange($event.target.innerText)" (paste)="pasteOnContenteditable($event)"></div>

Component.ts

@ViewChild('textBlockElement ', { static: false }) textBlockElement : ElementRef;

pasteOnContenteditable(e : any) {
   e.preventDefault();
   let clipboardData = e.clipboardData;
   let pastedText = clipboardData.getData('text');
   let textEl : HTMLElement = this.textBlockElement.nativeElement;
   textEl.innerText = textEl.innerText + pastedText;
}


textOnChange(textVal : string){
   console.log(textVal);
}

1 个答案:

答案 0 :(得分:0)

我尝试了您的情况,并找出了逻辑错误的地方。

代码中的问题是,您在文本末尾附加了文本,而不是找到光标位置。

请检查以下代码以解决您的问题。 (https://stackblitz.com/edit/angular-ivy-pnjtxp?file=src%2Fapp%2Fapp.component.html

在app.component.html

<div class="text-block" contenteditable #textBlockElement
 (input)="textOnChange($event.target)" 
 (paste)="pasteOnContenteditable($event)"></div>

在app.component.ts中

import { Component, VERSION, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  @ViewChild('textBlockElement ', { static: false }) textBlockElement : ElementRef;

pasteOnContenteditable(e : any) {
   e.preventDefault();
   let clipboardData = e.clipboardData;
   let pastedText = clipboardData.getData('text');
   let textEl : HTMLElement = this.textBlockElement.nativeElement;
  //  textEl.innerText = textEl.innerText + pastedText;
   this.insertAtCursor(textEl, pastedText);
}
 
 insertAtCursor (input, textToInsert) {
  // get current text of the input
  const value = input.innerText;
console.log('***********',value);
  // save selection start and end position
  const start = input.selectionStart;
  const end = input.selectionEnd;

  // update the value with our text inserted
  input.innerText = value.slice(0, start) + textToInsert + value.slice(end);

  // update cursor to be at the end of insertion
  input.selectionStart = input.selectionEnd = start + textToInsert.length;
}

textOnChange(textVal){
   console.log(textVal);
}
}