简体   繁体   English

角度材料mat-error无法显示消息

[英]Angular material mat-error cannot show message

I have 2 datetime picker, endDate cannot be less than startDate 我有2个日期时间选择器,endDate不能小于startDate

endDateAfterOrEqualValidator(formGroup): any {
    var startDateTimestamp: number;
    var endDateTimestamp: number;
    startDateTimestamp = Date.parse(formGroup.controls['startDateForm'].value);
    endDateTimestamp = Date.parse(formGroup.controls['endDateForm'].value);
    return (endDateTimestamp < startDateTimestamp) ? { endDateLessThanStartDate: true } : null;
  }

in html: 在HTML中:

<mat-form-field>
    <input matInput  name="endDate" id="endDate" formControlName="endDateForm" [(ngModel)]="endDate" [matDatepicker]="toDatePicker"
    placeholder="To Date">
    <mat-datepicker-toggle matSuffix [for]="toDatePicker"></mat-datepicker-toggle>
    <mat-datepicker disabled="false" #toDatePicker></mat-datepicker>
    <mat-error *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid<mat-error>
</mat-form-field>

with "mat-error", the message does not display. 如果出现“mat-error”,则不显示该消息。 I try to change by "small" 我尝试改变“小”

<small *ngIf="trainingDetail.hasError('endDateLessThanStartDate')">Not valid</small>

the message well. 信息很好。 Please advice me how to using mat-error 请告诉我如何使用mat-error

a mat-error only shows when a FormControl is invalid, but you have the validation on your formgroup. mat-error仅在FormControl无效时显示,但您在表单组上进行了验证。 So in that case you need to use a ErrorStateMatcher 因此,在这种情况下,您需要使用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);
  }
}

Also worth mentioning, it's not recommended to have two bindings, ie formControl and ngModel . 另外值得一提的是,不建议使用两个绑定,即formControlngModel Remove the ngModel and utilize the form control instead. 删除ngModel并使用表单控件。 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) 如果您稍后收到开始日期和结束日期,则可以使用patchValue (仅设置一些值来形成)或setValue (将所有值设置为表格)

mark in component the errorstatematcher: 在组件中标记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>

Here's a StackBlitz 这是StackBlitz

If you want to set a control as invalid from the .ts file manually... 如果要手动将.ts文件中的控件设置为无效...

HTML: HTML:

<mat-form-field class="full-width">
  <input matInput [formControl]="exampleFormControl" (change)="changeDetected()">
  <mat-hint>(Optional)</mat-hint>
  <mat-error *ngIf="exampleFormControl.hasError('invalid')">
      Must be a <strong>valid input</strong>!
  </mat-error>
</mat-form-field>

TS: TS:

import { FormControl } from '@angular/forms';

@Component({
  selector: 'derp',
  templateUrl: './derp.html',
  styleUrls: ['./derp.scss'],
})
export class ExampleClass {

  // Date Error Form Control
  exampleFormControl = new FormControl('');

  // Variable Check
  inputValid: boolean;

  changeDetected() {
    // Check if input valid
    if (this.inputValid) {
      console.log('Valid Input');
    } else {
      console.log('Invalid Input');
      // IMPORTANT BIT - This makes the input invalid and resets after a form change is made
      this.exampleFormControl.setErrors({
        invalid: true,
      });
    }
  }

  // CODE THAT CHANGES VALUE OF 'inputValid' //

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular Material Mat-error 显示有效输入错误,同时使用正则表达式验证 - Angular Material Mat-error Showing error for valid inputs, while validating with regex Angular2 / 4材料设计, <mat-error> 不工作 - 没有找到结果 - Angular2/4 material-design, <mat-error> not working - when no results found 当 http get 请求状态返回 404 时显示 Angular Material mat-error - Display Angular Material mat-error when http get request status returns 404 Mat-Error 首次打开表单时显示所需的验证错误消息 - Mat-Error Required validation error message shows when form is first open 为什么mat-error在MatDialog上工作但在普通页面上没有? - Why is mat-error working on MatDialog but not on normal page? 无法设置设置 Angular 材质垫-选择默认选项 - Cannot set set Angular Material mat-select default option 角材料,选择 mat-list-option 并显示所选 mat-list-option 的相应数据 - Angular material , to select mat-list-option and show the respective data of the selected mat-list-option 角度禁用按钮和mat输入错误消息 - Angular disabling button and mat-input error message 为什么只有单击两次按钮才能显示垫错误? - Why is my mat-error only shown if I click two times on button? 如何在 angular 材料中基于 mat 单选按钮选择显示输入字段 - How to show input fields based on mat radio button selection in angular material
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM