I have developed a directive specifically for case manipulation. The code I created successfully updates the visual value using _Renderer2, but I am facing an issue with formGroup.value. Even though the directive visually changes the value as expected, the original value is retained in the formControl. Consequently, when extracting data from the form using formGroup.value, all values appear in lowercase. Is there a way to address this discrepancy? Thank you
<form [formGroup]="formGroup">
<mat-form-field>
<input placeholder="Street" formControlName="streetName" matInput uppercase>
</mat-form-field>
</form>
import { Directive, ElementRef, Optional, Renderer2, Self } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
@Directive({
selector: "textarea[uppercase], input[uppercase]",
host: {
'(input)': 'writeValue($event.target.value)',
'(blur)': 'onTouched()',
}
})
export class UppercaseDirective implements ControlValueAccessor {
onChange = (_: any) => {
console.log("onChange", _)
};
onTouched = () => {
console.log("onTouched")
};
constructor(private _renderer: Renderer2, private _elementRef: ElementRef, @Optional() @Self() public ngControl: NgControl) {
ngControl.valueAccessor = this;
}
writeValue(value: any): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'value', this.transformValue(value));
}
registerOnChange(fn: (_: any) => {}): void {
this.onChange = fn;
}
registerOnTouched(fn: () => {}): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
}
private transformValue(value: string): string {
return typeof value === 'string'
? value?.toUpperCase()
: value;
}
}