Search code examples
angular6ngb-datepicker

Is there an onHidden event for the ngb-datepicker? If there isn't how do we add events to custom components in angular?


I am using the datepicker from this source: https://ng-bootstrap.github.io/#/components/datepicker/api

And I would like to check if the ngb-datepicker is closed because I need to change the text of the button where it is triggered.

template:

 <button (click)="dp.open(); changeText();">{{buttonText}}</button>
 <ngb-datepicker #dp 
     [(ngModel)]="model" 
     (onHidden)="changeButtonText2()"  <<---is this possible? >
/>

ts:

 import {Component} from '@angular/core';
 import {NgbCalendar} from '@ng-bootstrap/ng-bootstrap';

 @Component({
    selector: 'ngbd-datepicker-basic',
    templateUrl: './datepicker-basic.html'
 })

 export class NgbdDatepickerBasic {

   buttonText: string = 'Open Calendar'

 constructor(private calendar: NgbCalendar) {
 }

 changeText() {
   this.buttonText = 'The Calendar is Open';
 }

 changeButtonText2() {
   this.buttonText = 'Open Calendar'
 }
}

The ngx-bootstrap datepick have this but it seems the ngb-datepicker does not implement this feature. Can someone help me create a workaround so I don't have to use the ngx-bootstrap just for this? I already added some styling so...

Thanks :)


Solution

  • If you are using popup datepicker and only want to change text button

    <form class="form-inline">
      <button (click)="dpk.toggle()">{{ dpk.isOpen() ? 'The Calendar is Open' : 'Open Calendar' }}</button>
      <div class="form-group">
          <input class="form-control" placeholder="yyyy-mm-dd"
                 name="dp" [(ngModel)]="model" ngbDatepicker #dpk="ngbDatepicker">
      </div>
    </form>
    

    if you want to custom more code, use this:

    @ViewChild('dpk') dpk: NgbDatepicker;
    
      ngAfterViewInit() {
        this.dpk['close'] = () => {
          if (this.dpk['isOpen']) {
            // super origin event
            this.dpk['_vcRef'].remove(this.dpk['_vcRef'].indexOf(this.dpk['_cRef'].hostView));
            this.dpk['_cRef'] = null;
            this.dpk['_closed$'].next();
            // custom code
            console.log('closed');
          }
        };
      }