Search code examples
angulartypescriptforms

Force input field to return to former correct value on wrong input


My app.component.html goes like this:

Type a number below. If it is negative it will be rejected

<input type="number" class="form-control" id="valueId" value="{{ myValue }}" (change)="handleValueChange($event)">

and my app.component.test goes like this:

export class AppComponent {
  myValue: number = 7
  handleValueChange(event: any) {
    const newProposedValue = event.target.value
    if (newProposedValue >= 0) {
      this.myValue = newProposedValue
    }
  }
}

If I launch the app, type 5 in the field, hit enter, type -3 in the field, hit enter, I would like the field's content to return to 5, the former correct value.

How do I achieve this? I tried adding else { this.myValue = this.myValue} after the if to simulate a change and force a reloading of the view but that doesn't work.


Solution

  • Ok to use another state to maintain the previous successful input? Not tailored to Angular, so you'll have to modify it as needed...

    export class AppComponent {
      myCurrentValue: number = 0;
      myPreviousSuccessValue: number = 1; // or whatever start value you want
    
      handleValueChange(event: any) {
        this.myCurrentValue = event.target.value;
      }
    
      handleOnSubmit(e) {
        e.preventDefault();
        if (this.myCurrentValue > 0) {
          this.myPreviousSuccessValue = this.myCurrentValue;
        } else {
          this.myCurrentValue = this.myPreviousSuccessValue;
        }
      }
    
    }
    
    <input type="number" class="form-control" id="valueId" value="{{ myCurrentValue }}" (change)="handleValueChange($event)" (submit)="handleOnSubmit($event)">