如何解决 prime-ng 日历组件中的反应式表单验证问题?

How can I solve the reactive form validation issue in the prime-ng calendar component?

我正在使用反应式表单并尝试验证 startDate 和 endDate,但不幸的是,无效、已触及、脏、验证器等表单状态无法正常工作。我如何验证日期?

  1. 项目-settings.html

     <div class="notification">
       <div class=" p-formgroup-inline" [formGroup]="projectFormGroup">
           <div class="p-fluid p-formgrid p-grid">
     <div class="p-field p-col-12">
         <p-calendar id="startDate" [dateFormat]="'dd/mm/yy'" [showIcon]="true" [(ngModel)]="startDate"
             selectionMode="range" placeholder="Select start date & end date" [maxDate]="" inputId="startDate" appendTo="body" [monthNavigator]="true" [style]="{'width': '100%'}">
         </p-calendar>
     </div>
    
      <button pButton type="button"  class="p-button-primary" label="Download" (click)="downloadTimesheetData()"></button>
                  <small class="p-error" *ngIf="startDate.Validators.required"> Please enter a start date & end date.</small>
       </div>
    </div>
    
  2. 项目-settings.ts

      public downloadTimesheetData(): void {
             this.timesheetService.getAllTimsheets({ startDate: this.startDate[0], endDate: this.startDate[1] }).subscribe(
             data => {
                  saveAs(data, "report.csv");
                  this.toastrService.success("Successfully Downloaded", "Success", { timeOut: 2000 });
         }, err => {
                     this.toastrService.error("Something Went Wrong", "Error", { timeOut: 2000 });
                     throw err;           
                    });
       }
    

您不应该将 ngModel 与反应形式一起使用。您应该使用您在 Form 组中定义的 formControl。

在 html 中为开始日期和结束日期定义 formControlName

<p-calendar id="startDate" [dateFormat]="'dd/mm/yy'" [showIcon]="true" formControlName="startDate" selectionMode="range" placeholder="Select start date & end date" [maxDate]="" inputId="startDate" appendTo="body" [monthNavigator]="true" [style]="{'width': '100%'}">
</p-calendar>

this.projectFormGroup = new FormGroup({
     startDate: new FormControl (this.startDate, Validators.required),
     endDate: new FormControl (this.endDate, Validators.required),
})

然后您可以使用

检索表单控件的值
this.projectFormGroup.getRawValue();