Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force ngModel update when value did not change?

I want to limit number input to 0-100 range, but on input, not during validation. I'm using ngModel to bind value and emitt change event:

<input [ngModel]="value" (ngModelChange)="validate($event)" />

And then check if value exceeds given limits:

public validate(value) {
    if (value > 100)
        this.value = 100;
    if (value < 0)
        this.value = 0;
}

And this partialy works. However if I say try to input 150 and value will switch to 100, I can then input anything over 100, because model value remains 100, and so input value is not updated. Is there any way to manually force this update?

EDIT: I missed quite important bit here. This behaviour seems to only occur to input with type=number. Text input wont exceed 100. My workaround is as Faisal suggested using keypress event with preventDefault like so:

public keyPress(event) {
    let inputChar: number = +String.fromCharCode(event.charCode);
    if (this.value + inputChar > 100 || this.value + inputChar < 0) {
        // Exceeded limits, prevent input
        event.preventDefault();
    }
}
like image 731
K. Kowalczyk Avatar asked Sep 17 '25 06:09

K. Kowalczyk


1 Answers

I had the same problem and found a different solution that I liked more. As you said the problem is that the value in the model is the same before and after your function. What I did was to call Angular's change detection before I change the value so it registers a change. For this use the ChangeDetectorRef class and call its detectChanges method.

Thus, your function becomes :

public validate(value) {
    this.changeDetector.detectChanges();
    if (value > 100)
        this.value = 100;
    if (value < 0)
        this.value = 0;
}

And it works perfectly. Hope it helps.

like image 112
Romain Avatar answered Sep 19 '25 16:09

Romain