【问题标题】:Mat-Error not showing actual message in Reactive Forms when exceeding maxLength validation. Angular Material超过 maxLength 验证时,Mat-Error 未在反应式表单中显示实际消息。角材料
【发布时间】:2020-08-22 01:19:21
【问题描述】:

我可以看到我对 textarea 表单控件的验证在超过 100 个字符时变为红色,但是实际的 mat-error 消息未显示。它适用于所需的验证。 [编辑] 正确答案由下面的第一个答案解决。 "maxlength" 是所需的语法。

.ts

 descriptionFormGroup: FormGroup;
 descriptionCtrl = new FormControl('', [Validators.required, Validators.maxLength(100)]);

 this.descriptionFormGroup = this._formBuilder.group({
  descriptionCtrl: ['', [Validators.required, Validators.maxLength(100)]]
  });
  matcher = new MyErrorStateMatcher();

HTML 文件

<form [formGroup]="descriptionFormGroup" class="center-flex-wrapper">
        <ng-template matStepLabel>Description</ng-template>
        <mat-form-field>
            <mat-label>Description</mat-label>
            <textarea matInput formControlName="descriptionCtrl" placeholder="Your Description" required [errorStateMatcher]="matcher"></textarea>
            <mat-hint>Max length is 100 characters</mat-hint>
            <mat-error *ngIf="descriptionFormGroup.controls.descriptionCtrl.hasError('maxLength')">Max length exceeded</mat-error>
            <mat-error *ngIf="descriptionFormGroup.controls.descriptionCtrl.hasError('required')">Description is required</mat-error>
        </mat-form-field>
    </form>   

错误状态匹配器

export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));}}

【问题讨论】:

    标签: angular angular-material angular-reactive-forms


    【解决方案1】:

    maxLength 的 hasError 字符串全部小写。

    所以这个

    descriptionFormGroup.controls.descriptionCtrl.hasError('maxLength')
    

    应该是:

    descriptionFormGroup.controls.descriptionCtrl.hasError('maxlength')
    

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 2022-11-25
      • 2018-07-06
      • 1970-01-01
      • 2019-05-27
      • 2016-12-28
      • 2018-12-29
      • 2021-12-24
      相关资源
      最近更新 更多