Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Created September 12, 2019 17:45
Show Gist options
  • Save rajaramtt/2f1ef4f3b212cf3cb68b9c962dd6fb95 to your computer and use it in GitHub Desktop.
Save rajaramtt/2f1ef4f3b212cf3cb68b9c962dd6fb95 to your computer and use it in GitHub Desktop.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appFocusfirstInvalidfield]'
})
export class FocusfirstInvalidfieldDirective {
constructor(private el: ElementRef) { }
@HostListener('submit', ['$event'])
onFormSubmit() {
const invalidElements = this.el.nativeElement.querySelectorAll('.ng-invalid');
for (let j = 0; j < invalidElements.length; j++) {
const invalidElem = invalidElements[j];
if (invalidElem.innerText.trim() === 'Ethnicity') {
invalidElem.focus();
scroll(invalidElem); {
invalidElem.scrollIntoView();
}
return;
}
if (invalidElements.length !== 2) {
for (let i = 0; i < invalidElem.length; i++) {
if (!invalidElem[i].validity.valid) {
invalidElem[i].focus();
scroll(invalidElem[i]); {
invalidElem[i].scrollIntoView();
}
return;
}
}
} else if (j === 1) {
if (!invalidElem.validity.valid) {
invalidElem.focus();
scroll(invalidElem); {
invalidElem.scrollIntoView();
}
return;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment