【问题标题】:How to set caret position in contenteditable div in Angular 4?如何在 Angular 4 的 contenteditable div 中设置插入符号位置?
【发布时间】:2018-05-06 10:44:16
【问题描述】:
<div id="editable" contenteditable="true" class="search-input" [textContent]="query" (input)="query=$event.target.textContent" (keyup)="searchClient($event)" (focus)="open()"></div>

这是我的 HTML 代码,并把支持内容可编辑的 DIV。当我按下任意键时,会触发 searchClient($event) 方法并设置一些值。我需要设置值的插入符号(光标)结尾并聚焦它。

我尝试了几个示例,但我无法找出 Angular 4 的解决方案。

注意:我试过How to set caret(cursor) position in contenteditable element (div)?得到这个错误SearchComponent.html:6 ERROR TypeError: Failed to execute 'setStart' on 'Range': parameter 1 is not of type 'Node'.

【问题讨论】:

标签: html angular typescript contenteditable


【解决方案1】:

如果您使用 Renderer2 API,您可以处理此问题。

1º) 创建一个你想要关注的标签的变量,并创建一个事件来调用一个函数来改变光标位置。喜欢:

<div class="example" #tagDiv>
     I want to focus in here.
</div>
<button (onclick)="changeCursorLocation()"> Click here </button>

2º) 在组件中创建一个 ViewChild() 和函数:

  @ViewChild("tagDiv") tagDivField: ElementRef;
  changeCursorLocation(){
      const element = this.renderer.selectRootElement('#tagDiv', true);
      element.focus();
  }

渲染器2:(https://angular.io/api/core/Renderer2)

我没有运行这种特定的代码和平,但我过去做过类似的事情并且效果很好。所以,希望对大家有所帮助。

Obs:记得导入 Renderer2 和 ElementRef;

【讨论】:

    【解决方案2】:

    你可以用这个来改变它...

    <div id="editable" contenteditable="true" class="search-input" [textContent]="query" (input)="Revisedquery=$event.target.textContent" (keyup)="searchClient($event)" (focus)="open()"></div>
    

    也可以找到这个有用的链接来深入研究这个问题。
    https://github.com/angular/angular/issues/9796

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 2011-06-17
      • 2016-02-24
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 2018-05-31
      相关资源
      最近更新 更多