首页 > 解决方案 > 在 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);
    }
 }

这就是我想要实现的。谁能告诉一个更好的方法来做到这一点?

在此处输入图像描述

标签: javascripthtmlangularngx-editor

解决方案


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将返回startOffsetand endOffset。我们可以使用它在特定位置插入特定的字符串/字符。


推荐阅读