Tengo una entrada donde necesito eliminar símbolos que no sean numéricos
Aquí está el html del componente.
<input type="text" tabindex="0" class="search__input form-control-md + {{ class }}" [value]="config.value" [required]="config.required" [attr.maxlength]="config.maxLength" [attr.minLength]="config.minLength" (focusout)="onFocusOut($event)" (input)="onValueChange($event)" (keypress)="onValueChange($event)" (keyup.enter)="onEnter($event)" #inputElem />Aquí está el componente
export class TextFieldComponent implements OnInit, ControlValueAccessor { @Input() config: FormBase<string>; @Input() form: FormGroup; @Output() onChanged = new EventEmitter<boolean>(); @Input() class: string; configControl = new FormControl(); @Input() set value(value: string) { this._value = value; } get value(): string { return this._value; } private _value: string; constructor() {} ngOnInit() {} onFocusOut(event) { this.onValueChange(event); this.onChanged.emit(true); } onEnter(event) { this.onValueChange(event); this.onChanged.emit(true); } onValueChange(event) { this.changeValue(event.target.value); } writeValue(value) { this.value = value; } changeValue(value) { if (this.value === value) { return; } this.value = value; let result; switch (this.config.isNumber) { case true: result = value != null ? value.toString().replace(/[^0-9]/g, "") : null; console.log(result); this.onChange(result); break; default: this.onChange(value); } } onChange: any = () => {}; onTouched: any = () => {}; registerOnChange(fn) { this.onChange = fn; } registerOnTouched(fn) { this.onTouched = fn; } } Mi problema es que en el focusout , por ejemplo, este método changeValue funciona bien y elimina símbolos que no son números, pero en el evento de keypress de tecla veo que en la consola he reemplazado el valor, pero en la entrada, todavía veo letras. ¿Cómo puedo solucionar este problema?
Debe comprender qué está haciendo exactamente la pulsación de tecla aquí. El evento de pulsación de tecla se activa cuando se presiona una tecla que produce un valor de carácter y ejemplos de teclas que producen un valor de carácter son las teclas alfabéticas, numéricas y de puntuación.
Ejemplos de teclas que no producen un valor de carácter son las teclas modificadoras como Alt, Shift, Ctrl o Meta.
En el caso anterior, el evento de pulsación de tecla no se invocará y solo se llamará cuando se produzcan los valores de los caracteres.
Debe usar el evento keyUp o keyDown para rastrear las cosas de manera más efectiva.
Nota: consulte este enlace para ver la diferencia b/w keyup, keydown y keypress.
En su componente, acceda al elemento de entrada usando ViewChild
@ViewChild('inputElem') inputEl: ElementRef;Luego para establecer el resultado después de reemplazar
result = value != null ? value.toString().replace(/[^0-9]/g, '') : null; // update input value this.inputEl.nativeElement.value = result; console.log(result);