问题
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