我正在尝试仅为案例创建一个指令。我创建了以下代码,但尝试制作 formGroup.value 时遇到问题。该指令在视觉上改变了值(通过使用_Renderer2),但formControl仍然具有原始值,并且当使用formGroup.value从表单中获取数据时,值是小写的。有可能解决这个问题吗?谢谢
<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;
}
}