【问题标题】:How I can set focus on the element when I am setting it to content editable in Angular 6?当我将元素设置为 Angular 6 中可编辑的内容时,如何设置元素的焦点?
【发布时间】:2020-03-17 09:10:50
【问题描述】:

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

当标签元素的 contentEditable 属性为真时,如何设置焦点?

<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>

用户界面:

【问题讨论】:

    标签: javascript html angular typescript angular6


    【解决方案1】:

    我们可以使用ViewChildren 来获取所有跨度,通过放置一个模板引用,拾取选中的span 并将焦点设置到元素。

    所以我建议添加模板引用并在您的beforeEdit() 中传递标签的索引(我们从 ngFor 获取),以便我们在想要将焦点放在字段上时引用它:

    <!-- add template reference in below span tag --->
    <span [contentEditable]="underUpdateTagId==tag.id" ... #spans>
    <!-- pass index as from ngFor iteration to beforeEdit() -->
    <span *ngIf="underUpdateTagId!=tag.id" class="edit text-info" (click)="beforeEdit(tag, i)">
    <!-- more code --->
    

    在组件中我们引用spans,模板引用。并且当点击时指定传递索引的跨度应该被聚焦:

    @ViewChildren("spans") spans: QueryList<ElementRef>;
    underUpdateTagId = null;
    
    beforeEdit(tag, index) {
      this.underUpdateTagId = tag.id;
      // wait a tick
      setTimeout(() => {
        this.spans.toArray()[index].nativeElement.focus();
      });
    }
    

    STACKBLITZ

    PS,这将焦点放在开头,你可能想要它在结尾,如果是这样的话,也许这个问题可以帮助你:Use JavaScript to place cursor at end of text in text input element

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      相关资源
      最近更新 更多