1

There seems to be strange issue with ngModel. When you check out the example here: Plnkr

You see that when I try the limit the possible values from 1 to 5, resetting the input works always fine when entering a value higher than 5. Resetting to 1 works almost as well but does not so when the current value of the input is 1 or nothing. Then the ngModel behaves correctly but the input is not correctly updated.

Component class

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
       ...
       <input type="text"
              [(ngModel)]="testValue"
              onClick="this.select();"
              onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
    </div>
  `,
  directives: []
})
export class App {
  private changeValueTimeout;

  private _testValue:number = 0;
  private _testValueMax:number = 5;

  get testValue() {
    return this._testValue + 1;
  }
  set testValue(value: string) {
    clearTimeout(this.changeValueTimeout);
    var me = this;

    this.changeValueTimeout = setTimeout(() => {
      var numValue:number = Number.parseInt(value);
      if (numValue > me._testValueMax - 1){
        numValue = me._testValueMax;
      } else if (numValue < 1 || isNaN(numValue)){
        numValue = 1;
      }
      me._testValue = numValue - 1;
    }, 1000);
  }

  constructor() {}
}

Is this a HTML specific issue is there a problem in angular2 or so?

Chic
  • 9,836
  • 4
  • 33
  • 62
user39558
  • 141
  • 8

2 Answers2

0

If you open source code of your example, you will see this on input:

onkeypress="return event.charCode >= 48 && event.charCode <= 57"

If you remove that you will be able do add any chars, if not, your chars code must be between 48 and 57.

Vlado Tesanovic
  • 6,369
  • 2
  • 20
  • 31
  • This is not the issue as it was described. The limitiaton from 1 to 5 is just for demo purposes, it could be something like from 1 to 615 as well. – user39558 Jan 20 '16 at 13:55
0

This confusion is part of the reason why two-way data binding is not the default in Angular 2. You cannot tell who is updating the variable.

I would not use a getter/setter with ngModel. You can split out ngModel into a property and an event handler that can be used in the template.

[ngModel]="testValue"
(ngModelChange)="checkRange($event)"

Then you don't need to use a private variable or a getter function

Chic
  • 9,836
  • 4
  • 33
  • 62