Hay algunas restricciones en el campo de nombre, por lo que estoy tratando de validar el campo de nombre usando la directiva como se muestra a continuación. Dentro de la directiva, estoy usando una expresión regular para verificar el nombre válido y luego reemplazando el nombre válido en el cuadro de texto usando valueAccessor.writeValue(newVal)
Aquí el problema es cuando estoy tratando de escribir en medio de alguna palabra en el salto del cursor del cuadro de texto al final.
@Directive({ selector: '[validateName]', host: { '(ngModelChange)': 'onInputChange($event, false)', '(keydown.backspace)': 'onInputChange($event.target.value, true)', '(focusout)': 'removeClass()' } }) export class NameValidator { constructor(public model: NgControl,public renderer: Renderer, public el: ElementRef) { } onInputChange(event, backspace) { if (!backspace) { // Remove invalid characters (keep only valid characters) var newVal = event.replace(/^[0-9\s]/g, '').replace(/[^A-Za-z0-9_$]/g,''); // Add class for invalid name. if (/^[0-9\s]/g.test(event) || /[^A-Za-z0-9_$]/g.test(event)) { this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', true); } else { this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false); } // set the new value this.model.valueAccessor.writeValue(newVal); } } removeClass() { this.renderer.setElementClass(this.el.nativeElement, 'invalid-name', false); } }Eso viene del hecho de DefaultValueAccessor escribe a ciegas el valor del elemento, si hay un foco o no, selección o no. Tuve que lidiar con ese comportamiento yo mismo, ya que estaba usando un formulario que se guardaba automáticamente y tuve que anular DefaultValueAccessor y crear uno que solo escribiera valor si fuera diferente (no creo que funcione para usted , vea abajo) :
export const DEFAULT_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DefaultValueAccessor), multi: true }; @Directive({ selector: "input:not([type=checkbox])[formControlName],textarea[formControlName],input:not([type=checkbox])[formControl],textarea[formControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]", host: {"(input)": "onChange($event.target.value)", "(blur)": "onTouched()"}, providers: [DEFAULT_VALUE_ACCESSOR] }) export class DefaultValueAccessor implements ControlValueAccessor { onChange = (_: any) => { }; onTouched = () => { }; constructor(private _renderer: Renderer, private _elementRef: ElementRef) { } writeValue(value: any): void { const normalizedValue = value == null ? "" : value; // line bellow is the only line I added to the original one if ((this._elementRef.nativeElement as HTMLInputElement).value !== normalizedValue) this._renderer.setElementProperty(this._elementRef.nativeElement, "value", normalizedValue); } registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } registerOnTouched(fn: () => void): void { this.onTouched = fn; } setDisabledState(isDisabled: boolean): void { this._renderer.setElementProperty(this._elementRef.nativeElement, "disabled", isDisabled); } }Para su caso, es posible que deba lidiar con la selección de entrada:
let start=this.el.nativeElement.selectionStart; let end = this.el.nativeElement.selectionEnd; this.model.valueAccessor.writeValue(newVal); this.el.nativeElement.setSelectionRange(start,end);Tenga en cuenta que puede que no sea preciso ya que está modificando la entrada...