angulardatepickerngb-datepicker

Is there a way to use NgbDatepicker's navigateTo() on the component other than using it on ngAfterViewInit()?


I am using the NgbDatepicker

<ngb-datepicker #dp [(ngModel)]="scheduledStartDate" [ngModelOptions]="{standalone:true}">
</ngb-datepicker>

It can be done on ngAfterViewInit() like:

@ViewChild('dp') datepicker: NgbDatepicker;

ngAfterViewInit() {
    this.datepicker.navigateTo({ year: new Date().getFullYear(), month: new Date().getMonth(), day: new Date().getDate() });
}

But is there a way to use navigateTo() on some other function ??


Solution

  • You cannot use NgbDatepicker until it is initialised. To be sure that it is available, we have ngAfterViewInit hook. So if you want to do some initialisation, you can do it in ngAfterViewInit. But if you still want to use it from some function which is called before view initialisation (let's say constructor since you did not show us where you're calling it from), you can use setTimeout as a workaround but I don't recommend doing that. See below component for instance -

    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html'
    })
    export class AppComponent implements AfterViewInit {
    
      @ViewChild('dp') datepicker: NgbDatepicker;
      scheduledStartDate: NgbDateStruct = {year: 2222, month: 10, day: 10};
    constructor(private calendar: NgbCalendar) {
      console.log(this.datepicker? 'NgDatePicker is available': 'NgDatePicker not initialized');
      setTimeout(() => {
        this.datepicker.navigateTo({year:2090, month: 10});
      }, 1000);
    }
    ngAfterViewInit() {
        console.log(this.datepicker? 'NgDatePicker is available': 'NgDatePicker not initialized');
    }
    }
    

    Please check this stackblitz example which works just fine. The app.component.html has two buttons to navigate to two different years.

    Update:

    You can also use startDate in your <ngb-datepicker> -

    <div *ngIf="addEditForm">
        <ngb-datepicker #dp [(ngModel)]="scheduledStartDate"  [startDate]="scheduledStartDate" (navigate)="date = $event.next" *ngIf="addEditForm"></ngb-datepicker>
     </div>
    

    And then keep changing scheduledStartDate instead of using this.datepicker.navigateTo({})

    openAddForm() {
        this.addEditForm = true;
        this.scheduledStartDate = {year: 5555, month: 10, day: 10};
      }
    

    Refer to this api document to know more.