小编Chr*_*You的帖子

超过 maxLength 验证时,Mat-Error 未在反应式表单中显示实际消息。角材料

我可以看到我对 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();
Run Code Online (Sandbox Code Playgroud)

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>   
Run Code Online (Sandbox Code Playgroud)

错误状态匹配器

export class MyErrorStateMatcher implements ErrorStateMatcher {
isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
const isSubmitted …
Run Code Online (Sandbox Code Playgroud)

angular-material angular angular-reactive-forms

1
推荐指数
1
解决办法
2329
查看次数