1

I have an Angular 2 project with two input fields, greater than and less than. I want to check to ensure that the user input valid values that don't contradict each other for the filter, and I want to do that dynamically on the front end without the user having to submit the form.

To be specific, I want to ensure that the "Greater Than" input is not greater than the value inside the "Less Than" field.

How can I do so?

<form (submit)="onSubmit()" id="inputForm" class="form-group" class="row">

        <h3>Price Filters</h3>

        <span>Greater than:</span>
        <input type="number" name="greaterThanValue" [(ngModel)]="greaterThanValue" placeholder="0">

        <span>Less than:</span>
        <input type="number" name="lessThanValue" [(ngModel)]="lessThanValue">

        <input type="submit">

    </form>

1 Answer 1

4

You can use ngModelChange to get notified of changes

HTML:

<input type="number" name="greaterThanValue" [(ngModel)]="greaterThanValue" (ngModelChange)="onChange($event)" placeholder="0">
<span>Less than:</span>
<input type="number" name="lessThanValue" [(ngModel)]="lessThanValue" (ngModelChange)="onChange($event)">

app.ts:

public onChange(event: any): void {
    if (this.greaterThanValue > this.lessThanValue) {
      console.log('Incorrect');
      this.greaterThanValue = this.lessThanValue - 1;
    }
}

UPDATE: If you just want to display a message instead of adjusting values, you can set a flag and display something based on the flag value,

<div style="color: red" *ngIf="isInvalid">Please check your ranges</div>

public onChange(event: any): void {
    this.isInvalid = this.greaterThanValue > this.lessThanValue;
}

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Would there be a way to inform the user of their mistake instead of just adjusting the values?
Updated answer and demo
Cool! Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.