pokly
pokly

Reputation: 121

How to check if user input is less than max value in Angular 2

I want to create a range filter in Angular. The user should not be able to enter a minimum value, which is smaller than the maximum input value.

HTML:

<input type="text" class="form-control" formControlName="from" [placeholder]="Minimum" />

<input type="text" class="form-control" formControlName="to" [placeholder]="Maximum" />

I'm not sure what to do. I guess I have to create two variables in the .ts-file (minValue and maxValue). And then check directly in the HTML with *ngIf, if the minValue is smaller than the maxValue and then send an error.

Does someone has an idea how to solve it properly? Thank you very much

Upvotes: 2

Views: 1045

Answers (2)

Sivakumar Tadisetti
Sivakumar Tadisetti

Reputation: 5051

You can try like below

component.html

<form [formGroup]="frmGrp">
    <input type="number" formControlName="fromValue" [min]="toCtrl.value" [value]="getMinValue()">
    <input type="number" formControlName="toValue">
</form>

Component.ts

export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;

  frmGrp: FormGroup;
  fromCtrl: AbstractControl;
  toCtrl: AbstractControl;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.frmGrp = this.fb.group({
      fromValue: [0],
      toValue: [0]
    });

    this.fromCtrl = this.frmGrp.get('fromValue') as FormControl;
    this.toCtrl = this.frmGrp.get('toValue') as FormControl;
  }

  getMinValue() {
    if (this.toCtrl.value > this.fromCtrl.value) {
      this.fromCtrl.setValue(this.toCtrl.value);
    }
    return this.fromCtrl.value;
  }
}

Here is the working stackblitz

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22203

You need to set Validator on change of "from" formControl

Try like this:

ngOnInit() {
    ...
    this.contactForm.get("from").valueChanges.subscribe(val => {
      this.contactForm.get("to").setValidators(Validators.min(val));
    });
}

Working Demo

Upvotes: 2

Related Questions