我在 Angular 7 中使用 ngx-editor。我需要在单击参数列表中的参数时在光标位置插入 html。附件是我当前 View 的图像。现在,单击参数时,它会以如图所示的方式附加它。
我希望每个选定的参数都是单独的徽章,应在单个退格键中删除。此外,您还应该能够编写纯文本。
我现在就是这么做的。
<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
和 endOffset
。我们可以使用相同的方法在特定位置插入特定字符串/字符。
关于javascript - 在 ngx-editor 中,单击按钮时如何在光标位置插入 html block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59137789/