有时候页面搜索的时候,搜索框出来后希望输入框自动聚焦
<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()
方法就起作用了。