Greetings! I'm currently in the process of developing a collection of custom reactive form controls to make it easier for templates. So far, I've successfully created one using the ControlValueAccessor
interface. The form editing functionality is working smoothly, but I'm facing difficulties in displaying error messages. Can anyone provide suggestions on how to pass and display error messages within the HTML of custom controls?
Check out my code below:
input-form.component.html
<div style="font-size: 12px">
<mat-form-field appearance="outline">
<mat-label>{{ label }}</mat-label>
<input
matInput
[required]="required"
[readonly]="readonly"
[formControl]="textInputFormControl"
(input)="change()"
/>
</mat-form-field>
</div>
input-form.component.ts
import { Component, Input, OnChanges } from '@angular/core';
import {
ControlValueAccessor,
FormControl,
NG_VALUE_ACCESSOR,
} from '@angular/forms';
import { getErrorMessage } from '../form-fields.helper';
@Component({
selector: 'x-text-input',
templateUrl: './text-input.component.html',
styleUrls: ['./text-input.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: TextInputComponent,
},
],
})
export class TextInputComponent implements ControlValueAccessor {
public textInputFormControl = new FormControl('');
onTouched = () => {};
onChange: (_: string) => {};
@Input()
public label: string;
@Input()
public readonly: boolean;
public change() {
this.onChange(this.textInputFormControl.value);
this.onTouched();
}
writeValue(value: any): void {
this.textInputFormControl.setValue(value);
}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
setDisabledState(disabled: boolean) {
disabled
? this.textInputFormControl.disable({ emitEvent: false })
: this.textInputFormControl.enable({ emitEvent: false });
}
}
Many thanks!