0

我正在使用响应式表单并尝试验证 startDate 和 endDate,但不幸的是,无效、触摸、脏、验证器等表单状态不起作用。我如何验证日期? 下载按钮

  1. 项目设置.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. 项目设置.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;           
                    });
       }
    
4

1 回答 1

1

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

在 html 中为 startDate 和 endDate 定义 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();
于 2021-09-08T05:28:08.683 回答