Javascript 在Angular 6中将元素设置为“内容可编辑”时,如何将焦点设置在该元素上?

Javascript 在Angular 6中将元素设置为“内容可编辑”时,如何将焦点设置在该元素上?,javascript,html,angular,typescript,angular6,Javascript,Html,Angular,Typescript,Angular6,我使用Angular 6的contentEditable属性编辑元素的内容(在ngFor中) 当标记元素的contentEditable属性为true时,如何将焦点设置在标记元素上 <div class="tag" *ngFor="let tag of tags"> <span [contentEditable]="underUpdateTagId==tag.id" [textContent]="tag.title (input)="tag.title=$eve

我使用Angular 6的contentEditable属性编辑元素的内容(在ngFor中)

当标记元素的contentEditable属性为true时,如何将焦点设置在标记元素上

<div class="tag" *ngFor="let tag of tags">
   <span [contentEditable]="underUpdateTagId==tag.id" [textContent]="tag.title 
    (input)="tag.title=$event.target.textContent">
   </span>
   <span *ngIf="underUpdateTagId!=tag.id" class="edit text-info" (click)="beforeEdit(tag)">
         <i class="fas fa-pencil-alt"></i>
   </span>
   <span *ngIf="underUpdateTagId==tag.id" class="update text-success" (click)="editTag(tag)">
         <i class="fas fa-check save"></i>
   </span>
   <span class="delete text-danger" (click)="delete(tag)">
         <i class="fas fa-trash-alt"></i>
   </span>
</div>



我们可以使用
ViewChildren
来获取所有跨度,方法是放置模板引用,拾取选中的
span
,并将焦点设置为元素

因此,我建议添加模板引用,并在
beforeEdit()
中传递标记的索引(我们从ngFor获得),以便我们可以在希望将焦点放在字段上时引用它:


在我们引用的组件
中跨越了
,模板引用。单击时,指定传递索引的范围应聚焦:

@ViewChildren(“span”)span:QueryList;
underUpdateTagId=null;
编辑前(标记、索引){
this.underUpdateTagId=tag.id;
//等一下
设置超时(()=>{
this.span.toArray()[index].nativeElement.focus();
});
}

PS,这在一开始就确定了重点,你可能希望它在最后,如果是这样的话,也许这个问题可以帮助你: