如何在其他组件中重用为 mat datepicker 编写的验证方法

How to reuse the validation method written for mat datepicker in other components

在我的组件中,我有 2 个日期选择器,并且有开始日期和结束日期验证。此方法检查开始日期是否早于结束日期。此验证将适用于所有日期选择器。如何在其他组件中重用验证而不是在其他组件中一次又一次地编写相同的逻辑。

searchOrder.ts

comparisonEnddateValidator(): any {
    let ldStartDate = this.formGroup.value['covstartdate'];
    let ldEndDate = this.formGroup.value['covenddate'];

    let startnew = new Date(ldStartDate);
    let endnew = new Date(ldEndDate);
    if (startnew > endnew) {
      return this.formGroup.controls['covenddate'].setErrors({ 'invaliddaterange': true });
    }

    let oldvalue = startnew;
    this.formGroup.controls['covstartdate'].reset();
    this.formGroup.controls['covstartdate'].patchValue(oldvalue);
    return this.formGroup.controls['covstartdate'].setErrors({ 'invaliddaterange': false });
  }

  comparisonStartdateValidator(): any {
    let ldStartDate = this.formGroup.value['covstartdate'];
    let ldEndDate = this.formGroup.value['covenddate'];

    let startnew = new Date(ldStartDate);
    let endnew = new Date(ldEndDate);
    if (startnew > endnew) {
      return this.formGroup.controls['covstartdate'].setErrors({ 'invaliddaterange': true });
    }

    let oldvalue = endnew;
    this.formGroup.controls['covenddate'].reset();
    this.formGroup.controls['covenddate'].patchValue(oldvalue);
    return this.formGroup.controls['covenddate'].setErrors({ 'invaliddaterange': false });
  }

searchOrder.html

<mat-form-field appearance="outline">
    <mat-label> Covering Start Date </mat-label>
    <input
      matInput
      [matDatepicker]="CovStartdate"
      formControlName="covstartdate"
      (dateChange)="comparisonStartdateValidator()"
      required
    />
    <mat-datepicker-toggle
      matSuffix
      [for]="CovStartdate"
    ></mat-datepicker-toggle>
    <mat-datepicker #CovStartdate></mat-datepicker>
    <mat-error
      *ngIf="
        formGroup.controls['covstartdate'].hasError('invaliddaterange')
      "
    >
      <strong>Start date cannot be greater than end date</strong>
    </mat-error>
    <mat-error
      *ngIf="formGroup.controls['covstartdate'].hasError('required')"
    >
      Covering Start date is <strong>required</strong>
    </mat-error>
  </mat-form-field>

  <mat-form-field appearance="outline">
    <mat-label> Covering End Date </mat-label>
    <input
      matInput
      [matDatepicker]="CovEnddate"
      formControlName="covenddate"
      (dateChange)="comparisonEnddateValidator()"
      required
    />
    <mat-datepicker-toggle
      matSuffix
      [for]="CovEnddate"
    ></mat-datepicker-toggle>
    <mat-datepicker #CovEnddate></mat-datepicker>
    <mat-error
      *ngIf="formGroup.controls['covenddate'].hasError('invaliddaterange')"
    >
      <strong>End date cannot be earlier than start date</strong>
    </mat-error>
    <mat-error
      *ngIf="formGroup.controls['covenddate'].hasError('required')"
    >
      Covering End date is <strong>required</strong>
    </mat-error>
  </mat-form-field>
</div>

创建服务。然后创建一个验证日期选择器的通用验证器函数。

shared.service.ts

comparisonEnddateValidator(formGroup, startControlName, endControlName): any {
    let ldStartDate = formGroup.value[startControlName];
    let ldEndDate = formGroup.value[endControlName];

    let startnew = new Date(ldStartDate);
    let endnew = new Date(ldEndDate);
    if (startnew > endnew) {
        formGroup.controls[endControlName].setErrors({
            invaliddaterange: true
        });
        return formGroup;
    }

    let oldvalue = startnew;
    formGroup.controls[startControlName].reset();
    formGroup.controls[startControlName].patchValue(oldvalue);
    formGroup.controls[startControlName].setErrors({
        invaliddaterange: false
    });

    return formGroup;
}

然后从你的组件中调用这个函数 -

app.component.ts

comparisonEnddateValidator(): any {
    this.formGroup = 
        this.sharedService.comparisonEnddateValidator(this.formGroup, 'covstartdate', 'covenddate');
    }
}

您可以为案例处理和重用代码创建指令。这是重用组件的最佳方式。您可以在该组件本身中编写整个逻辑,并在您需要的任何地方重复使用。

<date-picker {... pass your conditions or data here.} 
             [condition]="startDate"
             [value]="startDataValue">
<date-picker>

你的指令可以包含这个

HTML 文件

<mat-form-field class="example-full-width" appearance="fill">
  <mat-label>Choose a date</mat-label>
  <input matInput [min]="minDate" [max]="maxDate" [matDatepicker]="picker">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

TS 文件


/** @Date picker directive with parent data passed for validations and values */

@Component({
  selector: 'date-picker',
  templateUrl: 'your template name',
})
export class DatePicker {
  @Input() minDate: Date = null;
  @Input() maxDate: Date = null;

  constructor() {}
}