Angular 6 - primeng <p-calendar> required condition

4.7k Views Asked by At

I am using the the PrimeNg calendar component in angular 6, and I wish to implement a [required] directive with a condition. once I set the "required" with a condition it is always sets to true, no matter what the condition is.

<p-calendar 
  [required]="Item.status === 'In Transit'"
  [(ngModel)]="Item.actualPickup" showTime="true" 
  hourFormat="24" showSeconds="true" dateFormat="dd/mm/yy" 
  [showIcon]="true" showButtonBar="true" hideOnDateTimeSelect="true">
</p-calendar>

any idea how can I do this in a template driven form?

2

There are 2 best solutions below

2
On BEST ANSWER

*ngIf

helps always in these kind of situations where you do not have a deep knowladge about directive.

Use

<p-calendar *ngIf = "myboolean == true" 
  [required]="Item.status === 'In Transit'"
  [(ngModel)]="Item.actualPickup" showTime="true" 
  hourFormat="24" showSeconds="true" dateFormat="dd/mm/yy" 
  [showIcon]="true" showButtonBar="true" hideOnDateTimeSelect="true">
</p-calendar>

<p-calendar *ngIf = "myboolean == false" 
  [required]="Item.status = true"
  [(ngModel)]="Item.actualPickup" showTime="true" 
  hourFormat="24" showSeconds="true" dateFormat="dd/mm/yy" 
  [showIcon]="true" showButtonBar="true" hideOnDateTimeSelect="true">
</p-calendar>
0
On

To dynamically add or remove the required attribute:

<p-calendar [required]="Item.status === 'In Transit' ? '' : null">

When the condition is true, this produces the required attribute without value (because of ''):

<p-calendar required>

else the required attribute is left out completely (because of null):

<p-calendar>