javascript - 在 ngx-editor 中,单击按钮时如何在光标位置插入 html 块
问题描述
我在 Angular 7 中使用 ngx-editor。单击参数列表中的参数时,我需要在光标位置插入 html。附件是我当前视图的图像。现在点击参数,它就是以这种方式附加它,如图所示。
我希望每个选定的参数都是单独的徽章,应该在单个退格键中删除。此外,您还应该能够编写纯文本。
这就是我现在正在做的事情。
<div class="bm-link-btn pull-right mt-10" [tooltip]="tooltipTemplate" placement="bottom" >
Parameters </div>
<ng-template #tooltipTemplate>
<div class="u-display-flex text-left">
<div class="p20" *ngFor="let item of paramsList$|async as params">
{{item?.category}}
<div class="bm-link-btn" *ngFor="let param of item.parameters">
<span (click)="onClickOfParams(param.value)">{{param.displayName}}
</span>
</div>
</div>
</div>
</ng-template>
onClickOfParams(value) {
document.getElementById('ngx-editor-textarea').focus();
let html = `
<div class="parameter-item"><div class="badge-plain-new">`+ value + `</div></div>`;
if (!document.execCommand("InsertInputText", false, '')) {
document.execCommand("InsertHTML", false, html);
}
}
这就是我想要实现的。谁能告诉一个更好的方法来做到这一点?
解决方案
HTML 代码:-->
<div class="field">
<label>Email Body</label>
<app-ngx-editor id="EmailBody" height="300px" minHeight="50px"
[spellcheck]="true" formControlName="EmailBody" #EmailBody>
</app-ngx-editor>
<span class="text-holder text-danger">
{{addNotificationTemplateFormErrors.EmailBody}}
</span>
</div>
组件:-->
@ViewChild('EmailBody') EmailBody: ElementRef;
this.cursorPositionedField = this.EmailBody;
if (this.addNotificationTemplateForm.value.EmailBody != null
&& this.addNotificationTemplateForm.value.EmailBody !== undefined
&& this.addNotificationTemplateForm.value.EmailBody !== '') {
const currentValue = this.cursorPositionedField.
_commandExecutor.savedSelection.
commonAncestorContainer.textContent;
const startOffset = this.cursorPositionedField.
_commandExecutor.savedSelection.startOffset;
const endOffset = this.cursorPositionedField.
_commandExecutor.savedSelection.endOffset;
newValue = [currentValue.slice(0, startOffset), insertField,
currentValue.slice(endOffset)].join('');
}
else {
newValue = insertField;
}
if (newValue.length <= ValidationConstant.notificationTemplate.
add.emailBody.maxLength) {
this.addNotificationTemplateForm.controls['EmailBody'].
markAsDirty({ onlySelf: true });
this.addNotificationTemplateForm.controls['EmailBody'].patchValue(newValue);
}
对于上述情况,this.EmailBody._commandExecutor.savedSelection
将返回startOffset
and endOffset
。我们可以使用它在特定位置插入特定的字符串/字符。
推荐阅读
- reactjs - 如何解决问题 Module not found: Can't resolve 'firebase/storage' in next.js (已经完成 yarn add firebase)
- json - 如何将具有嵌套结构的 Gatling jsonFeeder 转换为 json 请求正文?
- lua - 插入表 LUA 的不同方法
- javascript - How to write a switch statement for radio buttons
- javascript - For 循环中断一个不相关的数组
- pine-script - Pine Script V4 - Marketcap 标签的 Resolve_error "Fund"
- json - 是否可以在模式定义中引用 JSON 数据本身?
- sql - SQL WHERE 列值转换成大写字母
- php - 使用 Guzzle 在 Laravel 中创建代理
- api - 如何通过 api 或 java 库按范围/存储查询 Google Cloud 日志