I am facing a challenge with a rather complex form that contains multiple fields. Some of these fields are used to create logical blocks, and I would like to emphasize the surrounding div if any of these included fields are invalid. Can you suggest the best approach to accomplish this?
Currently, I have been attempting the following implementation, but I seem to be stuck at a certain point
import { Component } from '@angular/core';
import {FormBuilder, Validators} from "@angular/forms";
@Component({
selector: 'app-root',
template: `
<form [formGroup]="form">
<input formControlName="name">
<div class="div-address" [class.div-error]="DivHasError(divAddress)" #divAddress>
<div class="div-text">Address</div>
<input formControlName="addressType">
<div formGroupName="address">
<div>
<input formControlName="street">
</div>
<div>
<input formControlName="city">
</div>
</div>
</div>
</form>
`,
styles: [
`
input.ng-invalid {border-color: red;}
.div-error .div-text {color: red;}
`
]
})
export class AppComponent {
protected form = this.fb.group({
name: ['', Validators.required],
addressType: ['office', Validators.required],
address: this.fb.group({
street: ['', Validators.required],
city: ['', Validators.required],
})
});
constructor(private fb: FormBuilder) {
}
DivHasError(divElement: HTMLDivElement): boolean {
//TODO: Implement a more generic way to determine if any of the included fields are valid
// Return True if any included field is invalid, otherwise False
???
}
}
I am seeking a generic solution that does not involve manually listing all the fields in the "DivHasError" method. What would be the most efficient approach to achieve this?