javascript - 在插入符号位置插入文本 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);
}
解决方案
我已经尝试了您的方案,并发现了您的逻辑行为错误的地方。
您的代码中的问题是您在末尾附加了文本,而不是找到光标位置。
请检查以下代码以解决您的问题。(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);
}
}
推荐阅读
- sql - 使用查找优化来自多个表的选择性连接
- java - Java 中的 ActionListener 对我不起作用
- excel - 使用 VBA 循环遍历 Excel 中的 2 个列表以将选项卡数据从一个复制到另一个
- angular - 如何让 Fullcalendar 的外部事件在 Angular 中工作?
- django - 如何使用用户名或电子邮件登录 Django Rest Auth
- machine-learning - 使用分类和文本数据作为输入的机器学习分类
- java - Spring Boot:这安全吗?Api Key 作为 RequestHeader 与 Api Key 通过 Spring Boot Security
- c# - 时间从冬季时间更改为夏季时间时的 C# DateTime 转换
- javascript - 有没有办法解决我无法控制的 API 的 CORS 问题?
- python - Nuitka - 编译模块,包括预编译的 .so 库