首页 > 解决方案 > Contenteditable 光标在 ngfor 循环中移回到开头

问题描述

当我使用 [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 中绑定。

标签: javascriptangularangular7contenteditable

解决方案


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

  • 当您与网页交互时,“内容可编辑光标移回开头”是什么时候?
  • 你到底想发生什么?

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


某些事情可能会导致数组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 将不会重新渲染整个列表。

我从这里的这篇文章中学到了这一点


推荐阅读