Min and max value of input in angular4 application

后端 未结 9 1089
温柔的废话
温柔的废话 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:45

    [I assume the reader has basic knowledge of Angular2+ and Forms]

    It is easy to show a numerical input and put the limits, but you have to also take care of things may happen out of your predictions.

    1. Implement the tag in your 'html':
    
    
    1. But as Adrien said, still user can enter manually a wrong number. You can validate input by Validators easily. In your '.ts':
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    
    //many other things...
    
    this.myFG = new FormGroup({
       //other form controls...,
       rateFC  : new FormControl(0, [Validators.min(0), Validators.max(100)])
    });
    
    1. Up to now everything is ok, but it is better to let the user know the input is wrong, then draw a red line around the invalid input element by adding to your style:
    .form-control.ng-touched.ng-invalid{
        border:2px solid red;
    }
    
    1. And to make it perfect, prevent the user to submit the wrong data.
    
    

提交回复
热议问题