当前位置: 动力学知识库 > 问答 > 编程问答 >

angular2 - Value property on input element only updates once

问题描述:

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)

网友答案:

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

Plunker example

分享给朋友:
您可能感兴趣的文章:
随机阅读: