1 min readJun 19, 2023
The UppercaseDirective provided is responsible for converting the input text to uppercase as the user types. However, when using Reactive Forms, the value of the FormControl associated with the input field is not being updated correctly. To address this issue, you can manually update the value of the FormControl in addition to modifying the input's displayed value. Here's an updated version of the UppercaseDirective that handles Reactive Forms correctly:
import { Directive, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[appUppercase]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => UppercaseDirective),
multi: true
}
]
})
export class UppercaseDirective implements ControlValueAccessor {
private onChange: (value: any) => void;
private onTouched: () => void;
@HostListener('input', ['$event.target.value'])
onInput(value: string) {
const transformedValue = value.toUpperCase();
this.onChange(transformedValue); // Update the FormControl value
this.onTouched();
}
writeValue(value: any): void {}
registerOnChange(fn: any): void {
this.onChange = fn;
}
registerOnTouched(fn: any): void {
this.onTouched = fn;
}
}