ng-bootstrap datepicker unable to set default date before select

Viewed 2785

I am using ng-bootstrap date picker. this is my html for datepicker input

<input type="text"
id="datepicker{{i}}"
class="form-control"
formControlName="dateJoined"
ngbDatepicker
#incorporatedDatePicker="ngbDatepicker"
(click)="incorporatedDatePicker.toggle()"
(dateSelect)="onDateSelection($event)"
readonly>

However i am unable to set a default date to this input field before i select from the datepicker itself.

I am using reactive form here and i had already assigned NgbDateStruct Date as the form value

          const strDateTime = driver['JoinDate'];
          const arr = strDateTime.split(' ');
          const strDate = arr[0];
          const dateArr = strDate.split('/');

          const ngbDate: NgbDateStruct = {
            year: dateArr[2],
            month: dateArr[1],
            day: dateArr[0],
          }
          this.addDriverForm.patchValue({
            dateJoined: ngbDate
          })
2 Answers

value of dateJoined control should be the next structure:

this.dateJoined = new FormControl({
  year: 2020,
  month: 5,
  day: 16,
});

You need to verify that all the props are numbers, not strings.

const ngbDate: NgbDateStruct = {
  year: parseInt(dateArr[2], 10),
  month: parseInt(dateArr[1], 10),
  day: parseInt(dateArr[0], 10),
}

u can also use NgbDate class object

const defaultDate = new NgbDate(
   sDate.getFullYear(),
   sDate.getMonth() + 1,
   sDate.getDate()
);
Related