【问题标题】:Angular material mat-error cannot show message角材料垫错误无法显示消息
【发布时间】:2017-11-29 03:21:34
【问题描述】:

我有 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;
  }

在 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>

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

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

消息很好。请告诉我如何使用 mat-error

【问题讨论】:

    标签: javascript angular typescript angular-material


    【解决方案1】:

    mat-error 仅在 FormControl 无效时显示,但您的表单组已通过验证。所以在这种情况下你需要使用ErrorStateMatcher

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

    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);
      }
    }
    

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

    在组件中标记errorstatematcher:

    matcher = new MyErrorStateMatcher();
    

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

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

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

    <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

    【讨论】:

    • 非常感谢,这是一个很好的演示。但我将结束日期更改为无效日期。此错误消息不显示
    • 你把结束日期改成无效日期是什么意思?你能在我做的演示中演示一下吗?
    • 您在 ts 中的默认 startDate 是 2017-11-25T22:00:00.000Z。但在 UI 显示 2017 年 11 月 26 日(可能是时区)。我尝试先将 startDate 更改为 11/25/2017,然后更改无效的 endDate。显示错误。谢谢
    • @AJT_82 是否可以在此自定义验证中添加“必需”错误状态?感谢您的建议。
    • 这里有个问题,form: FormGroupDirective在isErrorState方法中有什么用。没用过,我们可以去掉吧?
    【解决方案2】:

    如果您想手动将 .ts 文件中的控件设置为无效...

    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:

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

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 2018-09-27
      • 2016-12-28
      • 2019-05-11
      • 2019-02-28
      • 2018-03-08
      相关资源
      最近更新 更多