D.Chakraborty
D.Chakraborty

Reputation: 35

How to stop the propagation of keyup events in Angular?

I am trying make an input field that takes only numbers and allows decimal values up to 2 decimal places. I want to stop the user inputs on the field after 2 decimal places. So that whatever the user enters, the value would not be entered. I am using keyup event because keypress actually takes the value late so that creates a problem with the checking. In the HTML I'm using:

<input
formControlName="WorkhoursPerWeek"    
class="mon-input-num"
(keyup)="validateNumber($event)"                                   
 />

In the Typescript the function goes as:

validateNumber(event: Event): Boolean {
    const DECIMAL_PLACES_REGEX = /^\d*\.?\d{0,2}$/;
    if (!DECIMAL_PLACES_REGEX.test(event.target["value"])) {
        return false;
    } else {
        return true;
    }
}

I tried to the user entry on the keyup function by using event.stopPropagation() and event.preventDefault(). Any ideas on how I can stop the user field entry?

Upvotes: 0

Views: 676

Answers (1)

user796446
user796446

Reputation:

As you say, your check is too late.

The simplest way to solve this is as follows:

NOTE: WorkhoursPerWeek should really be camelCase as workhoursPerWeek

validateNumber(event: Event): Boolean {
    const DECIMAL_PLACES_REGEX = /^\d*\.?\d{0,2}$/;
    if (!DECIMAL_PLACES_REGEX.test(event.target["value"])) {
        let myValue = this.form.controls.WorkhoursPerWeek.value;
        myValue = myValue.substring(0, myValue.length-1);
        this.form.controls.WorkhoursPerWeek.setValue(myValue);
    }
}

Upvotes: 1

Related Questions