简体   繁体   中英

Angular2 model binding not working

I try to update an input value in Angular 2, it works the first time the size value exceeds maxSize, but afterwords it does not work anymore. It seems like when I am setting this.size to some value the UI is not updated, am I overlooking something ?

HTML:

<input type="text" class="form-control" [value]="size" (input)="size = updateValue($event)">

Code:

export class BrushSizePicker {
@Input() minValue;
@Input() maxValue;
@Input() size;

increaseValue(event) {
this.size++;

this.checkValue();
}

decreaseValue(event) {
this.size--;

this.checkValue();
}

updateValue(event) {
this.size = parseInt(event.target.value);
this.checkValue();

return this.size;
}

private checkValue() {
if (this.size > this.maxValue) {
  this.size = this.maxValue;
}
if (this.size < this.minValue) {
  this.size = this.minValue;
}

}

EDIT: I logged what happened: checkValue is called every time with the correct input, and it returns the correct value. But the new value is not set into the input field / value field

While it may not solve the problem, the way you have implemented the input event can be simplified. I would have written it like this, side-effect free functions:

updateValue(event) {  // The method name with this change is a misnomer
   return this.checkValue(parseInt(event.target.value));
}

private checkValue(item) {
 if (item > this.maxValue) {
   return this.maxValue;
 }
 else if (else < this.minValue) {
   return this.maxValue;
 }
 return item;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM