javascript - 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 中绑定。
解决方案
您可能需要围绕您的问题提供更多背景信息:
- 当您与网页交互时,“内容可编辑光标移回开头”是什么时候?
- 你到底想发生什么?
无论哪种方式,我都会对可能发生的事情进行一些猜测......
某些事情可能会导致数组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 将不会重新渲染整个列表。
我从这里的这篇文章中学到了这一点。
推荐阅读
- java - Maven 依赖问题:提供和编译依赖一起工作
- javascript - Typescript 在整个项目中共享原始类型的自定义方法
- mysql - MySQL-如何根据不同列但同一行中的值选择列?
- jquery - jquery 镜头变焦完美定位
- r - 提高计算大型气候数据栅格堆栈的速度
- python - 在 Maya 中创建文本生成工具的问题
- javascript - 通过点击一些改变两个“div”的颜色,通过Javascript编程
- javascript - 如何使用 Jasmine 在 AngularJS 1.5+ 组件中测试 $scope.$on
- c# - 文件不可访问 - Visual Studio 2017
- gruntjs - 干净维护的连续步骤——删除临时文件?