javascript - 如何使用 Angular 编辑器在光标位置插入文本

标签 javascript css angular typescript

我想从下拉列表中添加选定的值,以显示在光标所在位置的文本框中。我正在使用。

enter code selectChangeHandler(event: any) {
this.selectedID = event.target.value;
// console.log("this.selectedID", this.selectedID);
this.arrayfordynamic += `<div>{{DV.Product.${this.selectedID}}}</div>`
console.log("this.arrayfordynamic", this.arrayfordynamic)
this.productDiscriptionArrayForID = `<div>${this.arrayfordynamic} </div> ${this.product.productDescription}`
// console.log("this.selectedIDwithDiscription-----", this.arrayfordynamic);
this.productForm.controls.des.setValue(this.productDiscriptionArrayForID);
}

我正在将下拉值设置到 Angular 编辑器文本中。但当我单击下拉值时,我不想在光标位置设置此值。请告诉我我们该如何做到这一点。

最佳答案

假设这是您的输入:

<input id="myInput"type="text">

您可以通过此函数获取位置:

function getCursor() {
  let cursor = document.getElementById('myInput');
  let start = cursor.selectionStart;
  let end = cursor.selectionEnd;
  return [start, end];
}

现在您必须编写一个函数来修补值:

function patchValue(selectedValue) {
  let currentValue = document.getElementById('myInput').value;
  let cursor = getCursor();
  let patchedValue = currentValue.substr(0, cursor[0]) + selectedValue + currentValue.substr(cursor[1]);
  document.getElementById('myInput').value = patchedValue;
}

您甚至可以选择一个范围,然后使用此代码将该范围替换为您选择的值。

这是一个例子:

function getCursor() {
  let cursor = document.getElementById('myInput');
  let start = cursor.selectionStart;
  let end = cursor.selectionEnd;
  return [start, end];
}

function patchValue() {
  let currentValue = document.getElementById('myInput').value;
  let cursor = getCursor();
  let patchedValue = currentValue.substr(0, cursor[0]) + document.getElementById('myPatch').value+ currentValue.substr(cursor[1]);
  document.getElementById('myInput').value = patchedValue;
}
<label>patch:</label><input id="myPatch"type="text">
<br>
<label>input:</label><input id="myInput"type="text">
<br>
<button onclick="patchValue()">patch</button>

关于javascript - 如何使用 Angular 编辑器在光标位置插入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70199012/

相关文章:

css - 服装文本 Telerik 按钮

angular - Angular 4中模型对象的Getter和Setter

angular - 在 Angular2 中使用父组件的模板

html - 强制 [innerHTML] 内容适应 div 宽度

javascript - 如何根据满足条件弹出图像

Javascript:检查多维数组中的对象是否具有特定属性,然后删除该对象

javascript - 如何正确检查表格

javascript - 如何在不使用 jQuery 的情况下将 HTML 附加到现有文件?

javascript - 处理在 iframe 内的新选项卡/窗口中打开

html - 两个并排的div,右边的宽度由其内容决定,左边的占用所有可用空间?