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

1
  • Minimum value can be anything and maximum value should not be less than minimum input value right? is that what your question? Commented Jul 13, 2020 at 9:22

2 Answers 2

2

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

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

Comments

1

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

Comments

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.