首页 > 解决方案 > 在插入符号位置插入文本 Contenteditable :Angular 8

问题描述

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

问题我怎样才能将复制的文本粘贴到当前光标位置。

请在下面找到我的代码。

组件.html

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

组件.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);
}

标签: javascriptangular

解决方案


我已经尝试了您的方案,并发现了您的逻辑行为错误的地方。

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

请检查以下代码以解决您的问题。(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);
}
}

推荐阅读