【问题标题】:Value property on input element only updates once输入元素上的值属性只更新一次
【发布时间】:2017-06-09 13:11:06
【问题描述】:

当我在输入元素中输入任何大于 1 的数字时——输入值变为 1(因为验证)。出于某种原因,这仅适用于我输入的第一个数字。例如,如果我输入 11,输入值将更改为 11,但它应该更改为 1。至少我记得它在 Angular 1 中是这样工作的。知道发生了什么吗?

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

这里是plunker (one.component.ts)

【问题讨论】:

  • 您的要求是什么?我听不懂你的第一行。
  • @micronyks,如果我输入的值大于 1,我希望输入元素上的数字变为 1

标签: angular angular2-template angular2-forms


【解决方案1】:

您的代码欺骗了更改检测。使用此解决方法,更改检测可以识别所有更改并更新您的 [value]="duration" 绑定。

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

Plunker example

【讨论】:

  • 是的,它有效!我爱你,好先生!感谢您的时间和知识!
  • 不客气。最后的detectChanges() 调用可能不是必需的。在事件发生之后,Angular 无论如何都应该运行更改检测。
猜你喜欢
  • 2018-09-10
  • 1970-01-01
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-12
  • 2015-03-25
  • 2020-07-18
相关资源
最近更新 更多