角度表单验证 - hasError min 不起作用

问题描述

如果值为 0,我想显示一个错误,但它不起作用。

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
     ]),});

有谁知道为什么这不起作用? Angular 文档说有一个最小值或最大值。

解决方法

试试这个:
直接指向控制器即可。

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

,

选项 1

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

选项 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

,

你犯的主要错误是你混合了模板驱动的表单和反应式表单。只需删除 [(ngModel)] 指令

<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>

注意行 form.get('windowHeight').hasError('min')。我们得到控制并检查它是否有错误 min