Reputation: 3464
When I enter any number larger than 1 into the input element -- input value changes to 1 (because of the validation). For some reason, this works only for the first number I enter. If I, for example, enter 11, input value changes to 11, but it should change to 1. At least that's how I remember it worked in Angular 1. Any idea what's happening?
import { Component } from '@angular/core';
@Component({
template:`
<input
type="number"
(input)="validate($event.target.value)"
[value]="duration">
<p>{{duration}}</p>`
})
export class OneComponent{
duration: number;
constructor(){
this.duration = 0;
}
validate(value){
if(value > 1) {
this.duration = 1;
}
else {
this.duration = value;
}
}
}
Here's plunker (one.component.ts)
Upvotes: 2
Views: 1484
Reputation: 657691
Your code is tricking change detection. With this workaround change detection recognizes all changes and updates your [value]="duration"
binding.
export class OneComponent{
duration: number;
constructor(private cdRef:ChangeDetectorRef){
this.duration = 0;
}
validate(value){
this.duration = -1;
this.cdRef.detectChanges();
if(value > 1) {
this.duration = 1;
}
else {
this.duration = value;
}
this.cdRef.detectChanges();
}
}
Upvotes: 1