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

Query: How to Force the input field to return to the former correct value on wrong input in Angular


Problem

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)">


Suggested blogs:

>How to make the dropdown for this button ADA accessible in Angular?

>How to update properties value with event in template Angular?

>Unit Test Angular Standalone Component, Overriding Provider not used

>How to Import componet's own module using Angular?

>Why component does not display variable of another component in Angular?

>What are the ways to pass parameters to Angular service?

>How to access variables in a function using Angular?

>How can I close a bootstrap modal using Angular?

>Fix: Strange compilation error with Typescript and Angular

>Uploading files and JSON data in the same request with Angular

>CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs

>CRUD Operation on Angular

>What is pipe in Angular?

>A Complete Guide To Angular Routing


Ritu Singh

Ritu Singh

Submit
0 Answers