简体   繁体   中英

Input event and reactive forms of angular

I have an input linked to an angular form, which uses an input event to call a function that converts to uppercase and validates that only letters and spaces are written, but in the form the last character is always left without converting or replacing, even when the function returns the correct value.

<input id="name" type="text" maxlength="60" (input)="funciones.convertOnlyText($event)" pInputText formControlName="name">

convertOnlyText(event) {        
        event.target.value = event.target.value.replace(/[^A-ZÁÉÍÓÚÑ a-záéíóúñ]+/g, '').trimLeft();
        let start = event.target.selectionStart;
        event.target.value = event.target.value.toUpperCase();
        event.target.selectionStart = start;
        event.target.selectionEnd = start;
}
this.form = new FormGroup({
    name: new FormControl({ value: null, disabled: false }, [Validators.required]),    
});

for example, if I write hello* in the input, the function returns HELLO, but in the form it would be HELLO*, or if I write only hello, the function returns HELLO but in the form it is HELLo.

When you place formControlName directive on input element It will internally implement DefaultValueAccessor. The DefaultValueAccessor automatically add input event for writing value to formControl.

That's why form control value and function return values are different.In order to sync form control with converted value you have to set the value manually using setValue or patchValue method like this:

Try this:

convertOnlyText(event) {        
        event.target.value = event.target.value.replace(/[^A-ZÁÉÍÓÚÑ a-záéíóúñ]+/g, '').trimLeft();
        event.target.value = event.target.value.toUpperCase();
        this.form.get('name').setValue(event.target.value, {emitEvent:false})
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM