【问题标题】:Contenteditable cursor move back to beginning in ngfor loopContenteditable 光标在 ngfor 循环中移回到开头
【发布时间】:2019-07-09 08:39:55
【问题描述】:

当我使用 [innerhtml] 在 ngFor 中绑定 html 数据时,Contenteditable 光标会回到开头。

<div *ngFor="article of articleLists">
  <div id="editor_article_{{article.id}}" contenteditable="true" [innerHtml]="article.data" class="form-control" autocomplete="off" placeholder="type your text here..."(input)="editableData($event.target.innerHTML, article.id, '')">
  </div>
</div>

但是如果我在组件中声明变量并绑定 [innerhtml],contenteditable 文本方向就可以了。但问题是变量应该是动态的才能在 ngFor 中绑定。

【问题讨论】:

  • 您必须自己跟踪插入符号的位置。 ngFor 中的内容会在每次循环执行时重建。你可以在这个网站上获得一些关于如何处理光标的灵感:codepen.io/neoux/pen/OVzMor

标签: javascript angular angular7 contenteditable


【解决方案1】:

您可能需要围绕您的问题提供更多背景信息:

  • 当您与网页交互时,“contenteditable 光标移回开头”
  • 您究竟希望发生什么?

无论哪种方式,我都会对可能发生的事情进行一些猜测......


某些事情可能会导致数组articleLists 以这样一种方式更新,即每个对象的引用都发生了变化。这对于 Angular 来说似乎是一个“新对象”,因为它通过引用来跟踪对象。因此 Angular 会重新渲染 *ngFor 循环的内容,并且插入符号的位置会丢失。

保留插入符号(或光标)位置的一种方法是防止 Angular 重新渲染 *ngFor 的内容(当它不需要时)。这可以通过使用 trackBy 函数改变 Angular 识别每个对象的方式来完成。

articleLists = [
  {
    id: 1,
    data: 'This is article 1',
  },
  {
    id: 2,
    data: 'This is article 2',
  },
  {
    id: 3,
    data: 'This is article 3',
  },
]

trackElement(index: number, element: any) {
  return element ? element.guid : null;
}
<div *ngFor="article of articleLists; trackBy: trackElement">
  <div id="editor_article_{{article.id}}" contenteditable="true" [innerHtml]="article.data" class="form-control" autocomplete="off" placeholder="type your text here..."(input)="editableData($event.target.innerHTML, article.id, '')">
  </div>
</div>

现在,如果对列表中对象的引用发生变化,但 id 保持不变,Angular 将不会重新渲染整个列表。

我是从这篇文章here了解到的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2011-01-24
    相关资源
    最近更新 更多