Angular10输入框对焦不起作用,AutoFocus指令

26 篇文章 2 订阅

有时候页面搜索的时候,搜索框出来后希望输入框自动聚焦

<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()方法就起作用了。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值