【发布时间】: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