在Angular中,可以通过自定义焦点指令来将焦点设置在表单的第一个无效输入框上。以下是一个示例解决方法:
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[appFocusInvalidInput]'
})
export class FocusInvalidInputDirective implements AfterViewInit {
constructor(private el: ElementRef) { }
ngAfterViewInit(): void {
const invalidInput = this.el.nativeElement.querySelector('.ng-invalid');
if (invalidInput) {
invalidInput.focus();
}
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { FocusInvalidInputDirective } from './focus-invalid-input.directive';
@NgModule({
declarations: [
AppComponent,
FocusInvalidInputDirective
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在,当表单加载时,焦点将自动设置在第一个无效输入框上。