Search code examples
angulartypescriptng-bootstrapbootstrap-datepicker

How to set custom date programmatically using ng bootstrap & angular 6?


Here I am trying to set a date programmatically using ng-bootstrap date picker

I tried some thing like this putting the custom date

this.model= {
  "year": 2018,
  "month": 8,
  "day": 15
}

I know it is not efficient way and there is one issue is that after selecting the giving the date picker is not navigating to that particular month.

Suppose If I choose 2nd jan 2018 then also it is staying in the current month it is not moving to jan. How can i solve these issues?

Below is my code & stack blitz link

.ts code

model: NgbDateStruct;
  date: {year: number, month: number};
  constructor(private calendar: NgbCalendar){

  }

   selectToday() {
    this.model = this.calendar.getToday();
  }

  select(){
    this.model= {
  "year": 2018,
  "month": 8,
  "day": 15
}

.html file

<ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next"></ngb-datepicker>

Solution

  • Just use [startDate]="model" binding so you will always get to the page when updating model:

    <ngb-datepicker #dp [(ngModel)]="model" [startDate]="model" (navigate)="date = $event.next"></ngb-datepicker>
    

    Or you might navigate the calendar manually via dp.navigateTo(model) method:

    <ngb-datepicker #dp [(ngModel)]="model" (navigate)="date = $event.next"></ngb-datepicker>
    
    <button class="btn btn-sm btn-outline-primary mr-2" (click)="selectToday(dp)">Select Today</button>
    <button class="btn btn-sm btn-outline-primary mr-2" (click)="select(dp)">Select Custom</button>
    

    And in controller:

    selectToday(dp) {
      this.model = this.calendar.getToday();
      dp.navigateTo(this.model);
    }
    
    select(dp){
      this.model = {
        "year": 2018,
        "month": 8,
        "day": 15
      }
      dp.navigateTo(this.model);
    }
    

    More about this: https://ng-bootstrap.github.io/#/components/datepicker/overview#navigation

    Updated example: https://stackblitz.com/edit/angular-knmpxc

    Manual solution: https://stackblitz.com/edit/angular-uvmjg4