简体   繁体   中英

Angular Material - number input - allow 0

I use this code in my HTML in order to make it possible to give in numbers started from 0 to inifinity:

<mat-input-container class="full-width-input" style="margin-left:5px;width:95%">
        <input matInput type="number" min="0" formControlName="ewBuild" required>
</mat-input-container>

in my Angular controller I use this:

ewBuild: new FormControl('', [Validators.required, Validators.minLength(1)]),

It is not allowed to give in 0, if I give in 1 oder 2 ... it is validated with success, but not with 0. What can I do in order to allow also 0?

There is a bug in the MinLength validator that reports the length as zero if the value is zero. See here . You don't need the min length validator when it is 1 because that is basically the same as required. I can't think of any reason to use min length with numeric inputs. You will need to implement a minimum value validator since the min property for input doesn't get used for validation. Something like:

minValueValidator(minValue: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        const valid = control.value >= minValue;
        return valid ? null : { 
            'minValue': { 
                'minimum': minValue, 
                'entered': control.value 
            } 
        };
    };
}

这适用于我现在的版本 12.2.16

ewBuild: new FormControl(null, [Validators.min(0), Validators.required]),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM