Chr*_*You 1 angular-material angular angular-reactive-forms
我可以看到我对 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 = form && form.submitted;
return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));}}
Run Code Online (Sandbox Code Playgroud)
小智 7
maxLength 的 hasError 字符串都是小写的。
所以这
descriptionFormGroup.controls.descriptionCtrl.hasError('maxLength')
Run Code Online (Sandbox Code Playgroud)
应该:
descriptionFormGroup.controls.descriptionCtrl.hasError('maxlength')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2329 次 |
| 最近记录: |