Mat-Error在超过maxLength验证时未在Reactive Forms中显示实际消息。角材料

问题描述 投票:0回答:1

我可以看到对textarea表单控件的验证在超过100个字符时变成红色,但是,实际的错误信息并未显示。它可以很好地进行所需的验证。

。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个回答
0
投票

maxLength的hasError字符串全部为小写。

所以这个

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

应该是:

descriptionFormGroup.controls.descriptionCtrl.hasError('maxlength')
© www.soinside.com 2019 - 2024. All rights reserved.