input元素的value属性只更新一次

时间:2017-01-24 16:22:13

标签: angular angular2-template angular2-forms

当我在输入元素中输入任何大于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)

1 个答案:

答案 0 :(得分: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

相关问题