Search code examples
angulartypescriptprimengprimeng-calendarprimeng-dialog

Programmatically open PrimeNG calendar in modal popup


How to make PrimeNG calendar at open state by default in modal popup ? Or how to trigger click event to open PrimeNG calendar which is in modal popup by typescript ?

If I used in HTML itself, it triggers the click event to open calendar by showoverlay(), but when using in modal popup, since popup is not in DOM element, it shows error as showoverlay() is not a function.


Solution

  • First, add a Viewchild to your calendar so that you can manipulate it to open it programmatically.

    Then, inside your method which opens the popup, call the showOverlay method on your calendar object to open it.

    Finally, surround this last line of code with a setTimout to delay its call.

    HTML

    <p-dialog header="Title" [(visible)]="display" [width]="500" [height]="500">
        <div class="row" style="height:300px;">
            Select a date
            <p-calendar #myCalendar [(ngModel)]="value"></p-calendar>
        </div>
    </p-dialog>
    
    <button type="text" (click)="showDialog()" pButton icon="fa-external-link-square" label="Choose date"></button>
    

    Ts

    @ViewChild('myCalendar') calendar;
    
    display: boolean = false;
    
    showDialog() {
        this.display = true;
        setTimeout(() => {
          this.calendar.showOverlay(this.calendar.nativeElement);
        }, 0);
    }
    

    See StackBlitz