angular2輸入框對焦不起作用,AutoFocus指令

有時候頁面搜索的時候,搜索框出來後希望輸入框自動聚焦

<input type="text" id="searchInput" [(ngModel)]="search.keyword" *ngIf="show"
       placeholder="輸入關鍵字搜索" autofocus
       (keyup)="myKeyup($event)">
       

卻發現這樣只能第一次的時候自動聚焦,以後就不可以了。
後來又嘗試了autoFocus directive的方法,設置聚焦必須在ngAfterViewInit方法中進行。

// autoFocus.directive.ts
import {AfterViewInit, Directive, ElementRef, Renderer2} from '@angular/core'

@Directive({
  selector: '[myAutoFocus]'
})

export class MyAutoFocusDirective implements AfterViewInit {
  constructor(private el: ElementRef) {
  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this.el.nativeElement.focus()
    }, 500)
  }
}

最後嘗試在代碼中手動聚焦,還是不行。找了很多原因,發現設置一個延遲就好了。

setTimeout(() => {
  document.getElementById('searchInput').focus()
}, 500)

這是因爲輸入框的隱藏於顯示我使用了*ngIf指令來控制,所以input在DOM中是動態的,如果一個元素不在DOM上面,對其設置 focus 也是無效的,所以我們設置一個500ms的延遲確保此時input已經在DOM中了,再調用focus()方法就起作用了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章