1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 【前端项目问题】angular 自定义“自动获取焦点”的指令时 focus不生效

【前端项目问题】angular 自定义“自动获取焦点”的指令时 focus不生效

时间:2022-08-01 18:09:57

相关推荐

【前端项目问题】angular 自定义“自动获取焦点”的指令时 focus不生效

focus不生效

一、问题重现二、问题解决

一、问题重现

前提:已经建好了自定义指令

html:

<input type="text" placeholder="自动获取焦点" appFocus/>

focus.directive.ts

import {Directive, ElementRef } from '@angular/core';@Directive({selector: '[appFocus]'})export class FocusDirective {constructor(e: ElementRef) {//获取input节点let input = e.nativeElement;//使input自动获取焦点e.nativeElement.focus()}}

input输入框不会自动聚焦!!!

二、问题解决

因为focus的执行可能不会及时出现,所以我们需要控制focus的执行时间。

focus.directive.ts

import {Directive, ElementRef } from '@angular/core';@Directive({selector: '[appFocus]'})export class FocusDirective {constructor(e: ElementRef) {//获取input节点let input = e.nativeElement;//使input自动获取焦点setTimeout(() => {//通过计时器将这个事件最后执行e.nativeElement.focus()}, 0);}}

问题解决!!!

以上是focus不生效的解决方案,请大家关注《项目问题》专栏,不定期改bug。

我会将自己平时项目中常见的问题以及笔试面试的知识在CSDN与大家分享,一起进步,加油。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。