Min and max value of input in angular4 application

后端 未结 9 1091
温柔的废话
温柔的废话 2020-12-08 13:01

I have an angular4 application with a form. In this one I have an input to enter a percentage. So, I want to block the input with value between 0 and 100. I tried to add

相关标签:
9条回答
  • 2020-12-08 13:55

    If you are looking to validate length use minLength and maxLength instead.

    0 讨论(0)
  • 2020-12-08 13:57

    Actually when you use type="number" your input control populate with up/down arrow to increment/decrement numeric value, so when you update textbox value with those button it will not pass limit of 100, but when you manually give input like 120/130 and so on, it will not validate for max limit, so you have to validate it by code.

    You can disable manual input OR you have to write some code on valueChange/textChange/key* event.

    0 讨论(0)
  • 2020-12-08 14:01

    You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz

    @HostListener('change') onChange() {
      const min = +this.elementRef.nativeElement.getAttribute('min');
    
      if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
        this.renderer2.setProperty(
          this.elementRef.nativeElement,
          'value',
          min + ''
        );
      }
    }
    

    Also listen for the ngModelChange event to do the same when the form value is set.

    @HostListener('ngModelChange', ['$event'])
    onModelChange(value: number) {
      const min = +this.elementRef.nativeElement.getAttribute('min');
      if (this.valueIsLessThanMin(min, value)) {
        const formControl = this.formControlName
          ? this.formControlName.control
          : this.formControlDirective.control;
    
        if (formControl) {
          if (formControl.updateOn === 'change') {
            console.warn(
              `minValueDirective: form control ${this.formControlName.name} is set to update on change
              this can cause issues with min update values.`
            );
          }
          formControl.reset(min);
        }
      }
    }
    

    Full code:

    import {
      Directive,
      ElementRef,
      HostListener,
      Optional,
      Renderer2,
      Self
    } from "@angular/core";
    import { FormControlDirective, FormControlName } from "@angular/forms";
    
    @Directive({
      // tslint:disable-next-line: directive-selector
      selector: "input[minValue][min][type=number]"
    })
    export class MinValueDirective {
      @HostListener("change") onChange() {
        const min = +this.elementRef.nativeElement.getAttribute("min");
    
        if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
          this.renderer2.setProperty(
            this.elementRef.nativeElement,
            "value",
            min + ""
          );
        }
      }
    
      // if input is a form control validate on model change
      @HostListener("ngModelChange", ["$event"])
      onModelChange(value: number) {
        const min = +this.elementRef.nativeElement.getAttribute("min");
        if (this.valueIsLessThanMin(min, value)) {
          const formControl = this.formControlName
            ? this.formControlName.control
            : this.formControlDirective.control;
    
          if (formControl) {
            if (formControl.updateOn === "change") {
              console.warn(
                `minValueDirective: form control ${
                  this.formControlName.name
                } is set to update on change
                  this can cause issues with min update values.`
              );
            }
            formControl.reset(min);
          }
        }
      }
    
      constructor(
        private elementRef: ElementRef<HTMLInputElement>,
        private renderer2: Renderer2,
        @Optional() @Self() private formControlName: FormControlName,
        @Optional() @Self() private formControlDirective: FormControlDirective
      ) {}
    
      private valueIsLessThanMin(min: any, value: number): boolean {
        return typeof min === "number" && value && value < min;
      }
    }
    

    Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.

     this.formGroup = this.formBuilder.group({
        test: [
          null,
          {
            updateOn: 'blur',
            validators: [Validators.min(5)]
          }
        ]
      });
    
    0 讨论(0)
提交回复
热议问题