angulartypescriptprimengangular-reactive-formsprimeng-calendar

How to set default date of prime-ng calendar when it is selected


I'm using the prime-ng calendar and I can't figure out how to set the default date when it is opened. The problem is that I know how to set a default value for the form field when the page is opened, but I want that field to stay empty. I only want a default field to be selected once the calendar is opened. Right now it defaults to the current datetime, and I was looking for the current date, but have the time always start at 12pm. If it helps, I'm using this in conjunction with Angular's form-builder.

I've looked at the prime-ng documentation(https://www.primefaces.org/primeng/#/calendar), but I can't seem to find anything related to this. I think there might be a solution with the onFocus Event, but that is me shooting in the dark because I don't know how to work with those.

This is my current calendar field

<fieldset class="form-group">
      <label for="expected-arrival-date">Expected Arrival Date</label><br>
      <p-calendar dateFormat="mm-dd-yy" hideOnDateTimeSelect="true" hourFormat="12" showTime="true" [showIcon]="true" [formControl]="requestForm.controls['expected_arrival_date']" name="expected-arrival-date" id="expected-arrival-date"></p-calendar>
</fieldset>

I expect the form value to initially be empty. When the calendar is opened up, I expect the default date to be the current date and the default time to be 12pm.


Solution

  • I can't test the code below because prime-ng is not on stackblitz or anything like that but you can try in your random.component.ts :

    ngOnInit() {
       this.requestForm.get('expected_arrival_date').setValue(new Date());
       // or this.requestForm.get('expected_arrival_date').patchValue(new Date());
    }
    

    Edit: if you just want to select a default date when the calendar is active, you can try the property defaultDate :

            <p-calendar dateFormat="mm-dd-yy" hideOnDateTimeSelect="true" hourFormat="12" 
        showTime="true" [showIcon]="true" 
    [defaultDate]="myDate" [formControl]="requestForm.controls['expected_arrival_date']" 
        name="expected-arrival-date" id="expected-arrival-date"></p-calendar>
    

    in ts, myDate will be something like :

    myDate = new Date(); // or whatever