I want to create a custom form control that handles any errors on itself. This means showing the error inside this component. I created a component which implements ControlValueAccessor. I can read the error form the form like this: form.controls.myfieldname.errors.aErrorName so I pass form.controls.myfieldname to my constom control.
Is there a better way to create field validation for a custom form control?
My custom control:
@Component({
selector: 'input-text2',
templateUrl: './input-text2.component.html',
styleUrls: ['/input-base2.scss', './input-text2.component.scss'],
providers: [
{ provide: NG_VALUE_ACCESSOR, multi: true, useExisting: InputText2Component }
]
})
export class InputText2Component implements ControlValueAccessor {
// The control field: form.controls.fieldname
@Input() field;
@Input() label: string;
@Input() errorMessage: string;
value: string;
valueChange: (value: any) => void;
_onTouched: (value: any) => void;
writeValue(value: any): void {
this.value = value;
this.createClasses(this.size);
}
registerOnChange(fn: (value: any) => void): void {
this.valueChange = fn;
}
registerOnTouched(fn: (value: any) => void): void {
this._onTouched = fn;
}
}
Layout:
<div *ngIf="field?.errors && field?.touched">
invalid
</div>
Form:
<form novalidate #form="ngForm">
<input-text2 [field]="form.controls.fieldname" name="fieldname" errorMessage="My error message" label="My label" [(ngModel)]="model"
custom-validator>
</input-text2>
</form>