【问题标题】:Angular2 model binding not workingAngular2模型绑定不起作用
【发布时间】:2016-01-09 13:12:38
【问题描述】:

我尝试在 Angular 2 中更新输入值,它在大小值第一次超过 maxSize 时起作用,但之后它不再起作用。似乎当我将 this.size 设置为某个值时,UI 没有更新,我是否忽略了什么?

HTML:

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

代码:

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;
}

}

编辑: 我记录了发生的事情:每次使用正确的输入调用 checkValue,它返回正确的值。但是新值没有设置到输入字段/值字段中

【问题讨论】:

  • 没有设置maxValueminValuecheckValue() 会做什么?他们可能会重置为null
  • 您可以在updateValue 方法中放置一些断点以查看它是否被调用并查看event.target.value 中的值。希望对你有帮助...

标签: data-binding angular


【解决方案1】:

虽然它可能无法解决问题,但您实现输入事件的方式可以简化。我会这样写,无副作用的函数:

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;
}

【讨论】:

  • 这永远不会分配给size
  • 对,我错过了。
猜你喜欢
  • 2016-10-02
  • 2012-05-31
  • 2016-08-14
  • 1970-01-01
  • 2017-03-15
  • 1970-01-01
  • 2018-08-15
  • 2018-02-28
  • 1970-01-01
相关资源
最近更新 更多