且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

角材料垫错误无法显示消息

更新时间:2023-02-02 12:23:53

a mat-error 仅在 FormControl 无效时显示,但您在表单组.因此,在这种情况下,您需要使用 ErrorStateMatcher

a mat-error only shows when a FormControl is invalid, but you have the validation on your formgroup. So in that case you need to use a ErrorStateMatcher

在您的情况下,它看起来像这样:

In your case it would look like this:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const invalidCtrl = !!(control && control.invalid);
    const invalidParent = !!(control && control.parent && control.parent.invalid);

    return (invalidCtrl || invalidParent);
  }
}

另外值得一提的是,不建议有两个绑定,即formControlngModel.删除 ngModel 并改用表单控件.如果您稍后收到开始日期和结束日期,您可以使用 patchValue(只需将一些值设置为表单)或 setValue(将所有值设置为表单)

Also worth mentioning, it's not recommended to have two bindings, i.e formControl and ngModel. Remove the ngModel and utilize the form control instead. If you receive your start date and end date at a later point, you can use patchValue (just set some values to form) or setValue (set all values to form)

在组件中标记错误状态匹配器:

mark in component the errorstatematcher:

matcher = new MyErrorStateMatcher();

至于您的自定义验证器,您不需要解析日期,只需检查结束日期是否小于开始日期:

As for your custom validator, you don't need to parse the dates, just check if end date is smaller than start date:

checkDates(group: FormGroup) {
  if (group.controls.endDate.value < group.controls.startDate.value) {
    return { endDateLessThanStartDate: true }
  }
  return null;
}

然后在模板中标记错误状态匹配器:

and then mark the error state matcher in your template:

<mat-form-field>
  <input matInput [matDatepicker]="picker2" type="text" formControlName="endDate" [errorStateMatcher]="matcher">
  <mat-datepicker-toggle matSuffix [for]="picker2"></mat-datepicker-toggle>
  <mat-datepicker #picker2></mat-datepicker>
  <mat-error *ngIf="myForm.hasError('endDateLessThanStartDate')">End date cannot be earlier than start date</mat-error>
</mat-form-field>

这是一个 StackBlitz

Here's a StackBlitz