Although everything functions correctly with a regular FormGroup, the issue arises when dealing with a FormArray as it fails to focus on the invalid input.
Here is how my form is initialized:
initForm() {
this.parentForm= this.fb.group({
childFormArray: this.fb.array([this.createchildForm()])
});
}
Following the initialization, the FormArray is set up like so:
createChildForm(data?: any): FormGroup {
var childForm = this.fb.group({
name: [data?.name? data?.name: '']
});
childForm .valueChanges.subscribe(value => {
var fieldWithValue = Object.keys(value).filter(key => value[key] == '');
fieldWithValue.forEach(conName => {
childForm .get(conName)?.addValidators([Validators.required]);
});
});
return childForm ;
}
My method for setting errors after clicking submit (a requirement);
assignError(){
this.parentForm.controls.childFormArray.value.forEach((v: any, index: number) => {
var array = this.parentForm.controls.childFormArrayas FormArray;
var item = array.at(index);
var emptyItems = Object.keys(v).filter(key => v[key] == '');
emptyItems.forEach(ele => {
if (ele != "section") {
item.get(ele)?.updateValueAndValidity({ emitEvent: false });
}
});
});
}
Additionally, I have created a validator that checks for invalid input and focuses on it.
import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[focusInvalidInput]'
})
export class FormDirective {
constructor(private el: ElementRef) { }
@HostListener('submit')
onFormSubmit() {
const invalidControl = this.el.nativeElement.querySelector('.ng-invalid');
if (invalidControl) {
invalidControl.focus();
}
}
}
Including its selector in the respective form:
focusInvalidInput (ngSubmit)="saveDetails()"
Inside the submit method, I call the error adding method:
saveDetails(){
assignError();
}
Despite all these efforts, focusing on the invalid inputs within the FormArray remains unsuccessful. When I log the invalidControl, it displays all the invalid inputs, which should not be the case possibly due to multiple invalid inputs causing confusion on which one to focus. Trying to utilize the .first() method resulted in an error stating that first is not recognized as a method.