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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47544505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:04:45  来源:igfitidea点击:

Angular material mat-error cannot show message

javascriptangulartypescriptangular-material

提问by quoc bao Pham

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. I try to change by "small"

使用“mat-error”时,不会显示该消息。我尝试通过“小”改变

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

the message well. Please advice me how to using mat-error

消息很好。请建议我如何使用 mat-error

回答by AJT82

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

amat-error仅在FormControl无效时显示,但您对表单组进行了验证。所以在这种情况下,你需要使用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, i.e formControland ngModel. Remove the ngModeland 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)

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

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>

Here's a StackBlitz

这是一个StackBlitz

回答by About7Deaths

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' //

}