为什么我的最小值和最大值验证没有触发?

Why my min and max validation is not firing?

我有如下模板:

<form class="form" [formGroup]="configWeightage">
  <div class="example-container">
    Enter value in between 0 to 100    <mat-form-field>
      <input
        matInput
        type="number"
        min="0"
        max="100"
        class="example-right-align"
        [formControlName]="weightageValue"
        id="weightage"
        required
      />
    </mat-form-field>
    <mat-error *ngIf="weightageValue.hasError('min(0)')" style="color: red"
      >Please enter greater than 0</mat-error
    >
    <mat-error *ngIf="weightageValue.hasError('max(100)')" style="color: red"
      >Please enter less than 100</mat-error
    >
  </div>
</form>

这是 class 文件

 import { Component } from '@angular/core';
    import { FormBuilder,FormGroup, Validators,FormControl } from '@angular/forms';
    
    /** @title Form field with prefix & suffix */
    @Component({
      selector: 'form-field-prefix-suffix-example',
      templateUrl: 'form-field-prefix-suffix-example.html',
      styleUrls: ['form-field-prefix-suffix-example.css'],
    })
    export class FormFieldPrefixSuffixExample {
      configWeightage:FormGroup;
      formBuilder : FormBuilder;
      weightageValueControl = new FormControl(['',Validators.required,Validators.min(0),Validators.max(100)]);
      hide = true;  
      constructor(private fb: FormBuilder) {}
      ngOnInit() {
        
       this.configWeightage = this.formBuilder.group(
        {
          'weightageValue' :this.weightageValueControl      
        }
    
       )
      }
    }

我假设当值不在 0 到 100 之间时会引发错误

但不会触发任何验证消息

这是相同的堆栈 bliz 代码,以便您可以 运行 并自行修复。

https://stackblitz.com/edit/angular-mat-form-field-dq8ntd?file=app/form-field-prefix-suffix-example.html

您应该在 Stackblitz 中修复一些错误和拼写错误:

  • [formControlName]

    中删除括号
  • <input> 中删除 minmax 属性,因为您已经使用 validators

    指定了它们
  • <mat-error>移入<mat-form-field>

  • 对于错误条件,你应该使用formGroupName.get('FormControlName').hasError('validatorName')

  • <mat-error>中删除style="color: red",这已经是错误消息的默认样式。

  • 更正错别字 this.formBuilder.groupthis.fb.group

    修复上述错误后Stackblitz