如何编写Angular自定义指令实现input输入框自动聚焦功能
Angular自动聚焦自定义指令修复方案
原代码问题说明
- 指令中错误使用了
@ViewChild:自定义指令是直接绑定在目标输入元素上的,不需要通过视图查询获取目标元素,@ViewChild仅用于组件类内部查询自身模板的子元素,不适用于指令场景 - 原代码中查询的
zone模板变量不存在,必然会导致取值为undefined,调用nativeElement时抛出错误
修正后的指令代码
import { AfterViewInit, Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appFocus]' }) export class FocusDirective implements AfterViewInit { // 构造函数注入ElementRef,直接获取当前指令绑定的DOM元素 constructor(private elementRef: ElementRef) { } ngAfterViewInit() { this.elementRef.nativeElement.focus(); // 如果遇到Angular Material组件渲染延迟导致聚焦失效,可以加0延迟定时器兜底 // setTimeout(() => this.elementRef.nativeElement.focus(), 0); } }
使用方法
你原有模板中的使用方式无需修改,直接给需要自动聚焦的输入框加上appFocus属性即可:
<div> <mat-form-field class="example-full-width" appearance="fill"> <mat-label>Saisie code barre</mat-label> <input appFocus matInput formControlName="barcode" placeholder="EAN..."> </mat-form-field> </div>
可选扩展:支持动态条件触发聚焦
如果需要根据业务状态动态控制聚焦时机,可以扩展指令增加输入属性:
import { AfterViewInit, Directive, ElementRef, Input } from '@angular/core'; @Directive({ selector: '[appFocus]' }) export class FocusDirective implements AfterViewInit { @Input() set appFocus(shouldFocus: boolean) { if (shouldFocus) { this.elementRef.nativeElement.focus(); } } constructor(private elementRef: ElementRef) { } ngAfterViewInit() { // 传入false时关闭默认初始化聚焦逻辑 if (this.appFocus !== false) { this.elementRef.nativeElement.focus(); } } }
扩展后的使用示例:
<!-- 满足条件时才触发聚焦 --> <input [appFocus]="formInitialized" matInput formControlName="barcode" placeholder="EAN...">
内容的提问来源于stack exchange,提问作者olivier
相关产品推荐
相关产品推荐

