Search code examples
angularformsvalidationangular2-form-validation

Angular Form Validation - hasError min doesnt work


I want to show an error if the value is 0 but it doesnt work.

HTML:

<mat-form-field>
      <input matInput type="number" placeholder="{{ 'device.new.windowHeight' | translate }}" [(ngModel)]="currentDevice.windowHeight" formControlName="windowHeight"> 
      <mat-error *ngIf="form.hasError('min')">0 is forbidden</mat-error>
  </mat-form-field>

TS:

form = new FormGroup({
    windowHeight: new FormControl(0, [
      Validators.min(1),
      Validators.max(10),
      Validators.required
     ]),
  });

Does anyone know why this is not working? The Angular docs says there is a min or max value.


Solution

  • Option 1

    <mat-error *ngIf="yourformgroupname.get('windowHeight').hasError('min')">0 is forbidden</mat-error>
    

    Option 2

    ***In your ts file***
    
    form: any;
    get windowHeight() {
       return this.form.get("windowHeight");
    }
    
    this.form = new FormGroup({
      windowHeight: new FormControl(0, [
        Validators.min(1),
        Validators.max(10),
        Validators.required
      ]),
    });
    
    ***HTML Template***
    
    <mat-error *ngIf="windowHeight.hasError('min')">0 is forbidden</mat-error>
    

    Stackblitz - https://stackblitz.com/edit/angular-mat-form-validation-eg-b34zsw?file=app/input-error-state-matcher-example.html