4
votes

I'm using the PrimeNG components w/Angular 4 but I'm running into an issue - that is how do I display the calendar when my button is clicked?

See Plunker

@Component({
selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <button pButton type="button" (click)="openCalendar($event)" label="Open Calendar"></button>
      <br/><br/>
      <p-calendar #calendar [(ngModel)]="value"></p-calendar>
    </div>
  `,
})
export class App {
  name: string;
  value: Date;

  @ViewChild('calendar')
  calendar: any;

  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }

  openCalendar(event: any) {
    console.log(event);
  }
}

I have tried getting the template element reference using @ViewChild('calendar'). I have also tried applying focus using @ViewChild('calendar#inputfield') but that doesn't work.

Any idea how to click a button to programmatically open the calendar?

2

2 Answers

11
votes

You can use showOverlay method on primeng calendar

openCalendar(event: any) {
  this.calendar.showOverlay(this.calendar.inputfieldViewChild.nativeElement);
  event.stopPropagation();
}

Modified Plunker

0
votes

The below code will work with the latest version of primeng (At the time this is posted)

In an HTML template

       <button pButton type="button" (click)="openCalendar($event)" label="Open Calendar"></button>
       <p-calendar
          #calendar
          [(ngModel)]="selectedDate"
          [readonlyInput]="true"
          (onSelect)="onSelectCal()"
          (onClose)="isEdit = false"
          appendTo="body"
        ></p-calendar>

In a .ts Controller

   import { Calendar } from "primeng/primeng";

   @ViewChild("calendar", { static: false }) private calendar: Calendar;

   openCalendar(event: any) {
     this.calendar.showOverlay();
     event.stopPropagation();
   }