Under my Angular 6 app , i\'m using Reactive Forms .
My purpose is when submitting , i want to set focus on first invalid input when
Try this:
import { Directive, HostListener, ElementRef} from '@angular/core';
@Directive({
selector: '[focusFirstInvalidField]'
})
export class FocusFirstInvalidFieldDirective {
constructor(private el: ElementRef) { }
@HostListener('submit')
onFormSubmit() {
const invalidElements = this.el.nativeElement.querySelectorAll('.ng-invalid');
if (invalidElements.length > 0) {
console.log(invalidElements[0]);
invalidElements[0].focus();
}
}
}
Remember to debug, see if element 0 is not your own form as it happened to me, so see right what field it is reporting as the first and put the position right.