In my project I'm having lots of forms each form contains 50 - 90 fields I'm using reactive form for each field there are set of validations. I have created a common component to display error to make the component readable as below.
<div class="position-relative">
<span class="input-icon material-icons-outlined">
person_outline
</span>
<input
type="text"
formControlName="username"
class="form-control"
aria-label="User Name"
/>
<app-form-error
[controlerName]="formControls['username']"
[errorMessages]="{ required: 'Please enter the user name' }"
></app-form-error>
</div>
This is my form error component:
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DoCheck,
Input,
} from '@angular/core';
import { AbstractControl, FormControl } from '@angular/forms';
@Component({
selector: 'app-form-error',
templateUrl: './form-error.component.html',
styleUrls: ['./form-error.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FormErrorComponent implements DoCheck {
@Input() controlerName: AbstractControl = new FormControl();
@Input() errorMessages?: { [key: string]: string };
errorMessage: string | null = null;
constructor(private cd: ChangeDetectorRef) {
this.controlerName = new FormControl();
}
ngDoCheck() {
this.renderErrorMessage();
}
private renderErrorMessage() {
this.errorMessage = null;
if (this.controlerName && this.controlerName.touched) {
for (const propertyName in this.controlerName.errors) {
if (
propertyName in this.controlerName.errors &&
this.controlerName.touched &&
this.errorMessages &&
propertyName in this.errorMessages
) {
this.errorMessage = this.errorMessages[propertyName];
break;
}
}
this.cd.markForCheck();
}
}
}
I have found one code and introduced Change detection but even though it is triggering multiple times. Consider the scenario im having two fields username and password if i touched both the field already if i start change something on the username both is getting triggered because they already touched. Will this cause performance issue for large form how to handle error message efficiently ?.