Angular Form Validation - hasError min doesnt work

2.8k Views Asked by At

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.

3

There are 3 best solutions below

0
On BEST ANSWER

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

0
On

Try this:
Just point directly to the controller.

<mat-error *ngIf="form.controls['windowHeight'].errors">0 is forbidden</mat-error>

0
On

The major error you are making is that you are mixing template-driven form and reactive forms. Just remove the [(ngModel)] directive

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

Note the line form.get('windowHeight').hasError('min'). We get the control and check if it hasError min