【问题标题】:Angular Form Validation - hasError min doesnt workAngular 表单验证 - hasError min 不起作用
【发布时间】:2021-04-12 14:54:23
【问题描述】:

如果值为 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 文档说有一个最小值或最大值。

【问题讨论】:

  • form 应该是 public property。您将其用作local variable
  • [(ngModel)] 还需要 name 属性。 (如果它在一个表单中)

标签: angular forms validation angular2-form-validation


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    &lt;mat-error *ngIf="form.controls['windowHeight'].errors"&gt;0 is forbidden&lt;/mat-error&gt;

    【讨论】:

      【解决方案3】:

      您犯的主要错误是您将模板驱动的表单和反应式表单混合在一起。只需删除[(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') 这一行。我们得到控件并检查它是否有Error min

      【讨论】:

        猜你喜欢
        • 2016-06-12
        • 2017-11-25
        • 1970-01-01
        • 2015-03-27
        • 2018-12-30
        • 2016-12-30
        • 1970-01-01
        • 2016-10-30
        • 2015-04-18
        相关资源
        最近更新 更多