Harsh Mendapara
Harsh Mendapara

Reputation: 313

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

I'm using the reactive form and trying to validate startDate and endDate, but unfortunately, form states like invalid, touched, dirty, validators, and so on are not working. How I can validate the dates? Download Button

  1. project-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. project-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;           
                    });
       }
    

Upvotes: 0

Views: 1109

Answers (1)

Sravan Ch
Sravan Ch

Reputation: 56

you are not supposed to use ngModel with reactive forms. You should use formControl that you define in the Form group.

Define formControlName in the html for the startDate and endDate

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

and then you can retrieve the values of the formcontrol using

this.projectFormGroup.getRawValue();

Upvotes: 1

Related Questions