PrimeNG calendar control ignores the dataType setting until the user modifies the selected dates

288 Views Asked by At

StackBlitz minimal repro (plus our hacky fix) here: https://primeng-calendar-demo-mejdfy.stackblitz.io

We're using the PrimeNG calendar control in multi-select mode.

To avoid hassles with conversion between client and UTC timezones, we've put the calendar in string mode by setting its dataType attribute to string.

<div class="p-fluid p-grid p-formgrid">
    <div class="p-field p-col-12 p-md-4">
        <label for="multiple">Choose multiple dates</label>
        <p-calendar
            #calendar
            [(ngModel)]="dates"
            selectionMode="multiple"
            dataType="string"
            inputId="multiple"></p-calendar>
    </div>
</div>
    
<h3>ngModel for calendar (initially Date, then string after user updates!)</h3>
<pre>{{ dates | json }}</pre>

Our problem is when the calendar control is first initialized. Say that our user is editing existing data, so we have a couple of dates that should initially be selected in the calendar control. So we initialise the ngModel of the calendar to an array of Date objects. That looks good on-screen - the calendar control does display those initial dates.

The problem is that the calendar control leaves its ngModel as an array of Dates, even though we've asked it to operate in "dataType" "string" mode. (Because we're showing the ngModel here by {{ model | json }}, the Date objects are being converted to their ISO-8601 string equivalents).

Bad - before user edits dates

Then, when the user modifies the date selection, the calendar control changes that ngModel to be an array of strings.

Notice that after the user edits the selected dates, the ngModel now contains the strings we expect.

Good - after user edits dates

We've found a pretty hacky workaround (it's in app.component.ts, commented out), which calls an internal function on the calendar component to trigger an update of the model to the expected format.

  ngAfterViewInit() {
    setTimeout(() => {
      // The following call seems to cause the calendar to update its model to the expected string dataFormat
      this.calendar.updateModel(this.calendar.value);
    });
  }

Also interested to know if anyone has suggestions for improvements to that fix?

Any ideas whether this is a PrimeNG bug or expected behaviour? Are we missing some config or lifecycle management in our minimal repro? Any suggestions?

Thanks!

0

There are 0 best solutions below