[FIXED] How to apply condition on view and dateFormat attribute on prime ng p-calendar control?

Issue

I have to use prime-ng p-calendar on turbo table rows which can have two different date format – mm/yy and mm/dd/yy depending on period field value. For now, I have added this control twice and rendered control based on period field condition as shown below.

<p-calendar *ngIf="Period.length == 15" name="period"
  id="period"
  selectionMode="range"
  view="month"
  appendTo="body"
  dataType="string"
  formControlName="period"
  [showIcon]="true"
  [monthNavigator]="true"
  [yearNavigator]="true" 
  [dateFormat]="mm/yy"
  placeholder="Choose">
</p-calendar>

<p-calendar *ngIf="Period.length == 20" name="period"
  id="period"
  selectionMode="range"
  view="date"
  appendTo="body"
  dataType="string"
  formControlName="period"
  [showIcon]="true"
  [monthNavigator]="true"
  [yearNavigator]="true"  
  dateFormat="mm/dd/yy"
  placeholder="Choose">
 </p-calendar>

My question is how can I use one control that works for both date format? I know I need to apply condition on view and dateFormat attribute but I am not able to make it work.

Solution

You can bind value and use ternary operator in your dateFormat. Basically you bind dateFormat to some condition, which in this case might be with a ternary (You can chain as many as you like but code can get unreadable preety fast).

Code will look like this:

<p-calendar 
  name="period"
  id="period"
  selectionMode="range"
  view="date"
  appendTo="body"
  dataType="string"
  formControlName="period"
  [showIcon]="true"
  [monthNavigator]="true"
  [yearNavigator]="true"  
  [dateFormat]="
  Period.length == 20 ? 'mm/dd/yy' : 
  Period.length == 15 ? 'mm/yy' : 
  'default value'"
  placeholder="Choose">
 </p-calendar>

just make sure that you provide some default value if Period will have no length or length will be different than any of these values. And upon component initialization of the view Period should not be undefined if the condition really depends on the value of it.

Answered By – Beka Kalandadze

Answer Checked By – Cary Denson (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published