Angular and Typescript - set cursur position multiple child element in contenteditable div(tried almost all articles)

拜拜、爱过 提交于 2020-08-05 17:38:07

问题


Can some one help me to get this resolved? Here is the stackblitz code I am working

If you know any workaround, please let me know.

I have searched almost all the articles in stackoverflow but none worked for me..I have a contenteditable div and when user types 'foo' it's automatically changes to bar(this changes based on some condition) and it can be multiple tags (child elements) too.

The Caret/cursur keeps going to start position and typing backward.can anyone help me to get this resolved in Angular(Typescript)?I had to choose div instead of textarea as I have links.

Output should look like below except the Caret postion

Typescript code as below

getUpdatedContent(event: KeyboardEvent) {   this.divcontent = (event.target as HTMLInputElement).innerHTML.replace('foo', '<a href="www.bar.com" title="Description">bar</a>'); }

Component/Html Code as below.

<div id="box" #tagDiv (keyup)="getUpdatedContent($event)" contenteditable [innerHTML]="divcontent" (focusout)="onfocusout()"></div>

or

<div id="box"  (blur)="getUpdatedContent($event.target.innerHTML)" contenteditable [innerHTML]="divcontent" (focusout)="onfocusout()" ></div>

I have tried several attempts

Typescript Code

@ViewChild("tagDiv") public tagDiv: ElementRef;
this.renderer.selectRootElement('#tagDiv').focus();

or

this.renderer.selectRootElement('#tagDiv',true).focus();




(event.target as HTMLInputElement).focus();
document.execCommand('selectAll', true, null);
document.getSelection().collapseToEnd();



<div id="box" contenteditable="true" [textContent]="model" (input)="model=$event.target.textContent"></div>


 @HostListener('keyup') 
 @HostListener('blur')  
 @HostListener('input') onInput() {

  this.model = this.model.replace('foo', '<a href="www.bar.com" title="Description">bar</a>');

  }

回答1:


here's one of the answer from StackOverflow

setCaretToEnd(target/*: HTMLDivElement*/) {
  const range = document.createRange();
  const sel = window.getSelection();
  range.selectNodeContents(target);
  range.collapse(false);
  sel.removeAllRanges();
  sel.addRange(range);
  target.focus();
  range.detach(); // optimization

  // set scroll to the end if multiline
  target.scrollTop = target.scrollHeight; 
}

Here's the updated stackblitz plunker



来源:https://stackoverflow.com/questions/62799054/angular-and-typescript-set-cursur-position-multiple-child-element-in-contented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!