Sarjerao Ghadage
Sarjerao Ghadage

Reputation: 1544

How to update event.target.value on keypress?

I am working to make postal code validation but I am not able to get updatedValue using event.target.value its showing oldValue

HTML code:

<input type="text"  style="color:black !important;width:100%;" (keypress)="numericOnly($event);" name="fname" [(ngModel)]='value' autofocus>

.ts file

 numericOnly(event): boolean {
        console.log("element", event);
        console.log('element.value', event.target.value);
        let patt = new RegExp("^[a-z A-Z 0-9]*-?[a-z A-Z 0-9]*$");
        console.log('this.value', this.value);
        let result = patt.test(event.target.value);
        console.log('result', result)
        if (result == false) {
            // event.target.value = this.value
            // this.value = event.target.value;
            const val = <string>event.target.value
            if (val && val.length > 0) {
                this.value =  event.target.value;
                event.preventDefault();
            }

        }
        return result;
    }

when I trying to access the target value using event.target.value its giving oldVlaue i want to get recently typed value on keypress event.whenever I used keyup event its updating ngModel which I don't want.

enter image description here

Upvotes: 1

Views: 4668

Answers (1)

jeprubio
jeprubio

Reputation: 18002

I would change [(ngModel)]='value' to [ngModel]='value' so that the model would not be updated on changes and then use (keyup).

Template code:

<input type="text" style="color:black !important;width:100%;" (keyup)="numericOnly($event);" name="fname" [ngModel]='value' autofocus>

As long as your numericOnly method updates your model (this.value) when the condition is met (as is doing now) you don't need the two-way data binding of ngModel.

Upvotes: 1

Related Questions