簡體   English   中英

當我將元素設置為在 Angular 6 中可編輯的內容時,如何設置元素的焦點?

[英]How I can set focus on the element when I am setting it to content editable in Angular 6?

我正在使用 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 獲取它),所以當我們想要將焦點放在字段上時可以引用它:

<!-- 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();
  });
}

堆棧閃電戰

PS,這將焦點放在開頭,你可能想要它在結尾,如果是這種情況,也許這個問題可以幫助你: Use JavaScript to place cursor at end of text in text input element

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM