I have number input field and I want to restrict it so max value will be 100. So When user types number by number I want it to be restricted in real time. For this I'm using (ngModelChange)
.
Example:
Here is html code:
<!-- NOT WORKING -->
<input type="number"
class="form-control"
maxlength="3"
[(ngModel)]="period"
(ngModelChange)="onValueChange()"
id="period" placeholder="0" min="0"
max="100" step="1" name="period">
<!-- WORKING -->
<p>{{period}}</p>
It's controller:
public period: number;
onValueChange() {
if (this.period > 100) this.period = 100;
}
This will update period but only once. If I continue to type more numbers it wont update the input field. Also maxlength="3"
is not working
I tried the same concept but on paragraph and it is working. Probably the problem is only on input field.
Since You updating the model value inside ngModelChange the model value is out of sync with view value. try updating the model value asynchronusly inside settimeout.
onValueChange() {
setTimeout(()=>{
if (this.period > 100) this.period = 100;
})
}