0

I am using Angular Bootstrap datepicker control to choose date. I want to set default date in the control when the form is loaded.

Here is my HTML code:

<div class="input-group">
  <input class="form-control" placeholder="dd-mm-yyyy" id="startDate" name="startDate"
    formControlName="startDate" [(ngModel)]="selectedStartDate" ngbDatepicker
    #d="ngbDatepicker" [ngClass]="{ 'is-invalid': submitted && f.startDate.errors }">
  <div class="input-group-append">
    <button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
  </div>
</div>

I have also used two service for redering date in datepicker:

import { Injectable } from '@angular/core'; import { NgbDateAdapter, NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';

/**
 * This Service handles how the date is represented in scripts i.e. ngModel.
 */
@Injectable()
export class CustomAdapter extends NgbDateAdapter<string> {
    
 readonly DELIMITER = '/';
    
 fromModel(value: string | null): NgbDateStruct | null {
  if (value) {
   let date = value.split(this.DELIMITER);
   return {
    day: parseInt(date[0], 10),
    month: parseInt(date[1], 10),
    year: parseInt(date[2], 10)
   };
  }
  return null;
 }
    
 toModel(date: NgbDateStruct | null): string | null {
  return date ? date.day + this.DELIMITER + date.month + this.DELIMITER + date.year : null;
 }
}
    
    
/**
 * This Service handles how the date is rendered and parsed from keyboard i.e. in the bound input field.
 */
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {
    
 readonly DELIMITER = '-';
    
 parse(value: string): NgbDateStruct | null {
  if (value) {
   let date = value.split(this.DELIMITER);
   return {
    day: parseInt(date[0], 10),
    month: parseInt(date[1], 10),
    year: parseInt(date[2], 10)
   };
  }
  return null;
 }
    
 format(date: NgbDateStruct | null): string {
  let dDay = "";
  let mMonth = "";
    
  if (date !== null) {
   if (date.day <= 9) {
    dDay = "0" + date.day;
   }
   else {
    dDay = (date.day).toString();
   }
    
   if (date.month <= 9) {
    mMonth = "0" + date.month;
   }
   else {
    mMonth = (date.month).toString();
   }
  }
    
  //return date ? date.day + this.DELIMITER + date.month + this.DELIMITER + date.year : '';
  return date ? dDay + this.DELIMITER + mMonth + this.DELIMITER + date.year : '';
 }
}

In my component, OnInit method I have used the below code to set default date, which is: this.frmTransferHistory.controls["startDate"].setValue(new Date());

But it does not work and shows the bellow error:

ERROR TypeError: value.split is not a function at CustomAdapter.fromModel (date-formatter.service.ts:14) at NgbInputDatepicker.writeValue (ng-bootstrap.js:4465) at setUpControl (forms.js:1509) at FormGroupDirective.addControl (forms.js:5253) at FormControlName._setUpControl (forms.js:5835) at FormControlName.ngOnChanges (forms.js:5780) at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.js:1520) at callHook (core.js:2583) at callHooks (core.js:2542) at executeInitAndCheckHooks (core.js:2493)

enter image description here

4
  • The issue is not with bootstrap datepicker. I would just use DatePipe, find my full answer below. Commented Jul 18, 2021 at 11:04
  • You could set the type of value to string | any Commented Jul 18, 2021 at 11:44
  • @manu, first: don't use together FormControl and [(NgModel)], second you're puttin gthe code to make that the "control" mannage strings -instead ngbDate-, not Date object Commented Jul 18, 2021 at 13:21
  • 2
    the CustomDateParserFormatter is to convert ngbDate to string to manage when you enter the date manually (you can left as the exmple), the CustomAdapter is to convert the ngbDate to "whatever you want". If you want to manage Date object of javascript you need change it -seee the docs about adapters: ng-bootstrap.github.io/#/components/datepicker/… Commented Jul 18, 2021 at 13:26

1 Answer 1

1

In your component add the DatePipe to the constructor and initialize your date:

constructor(
  private datePipe: DatePipe
) { }

yourForm: any = {
  date: this.datePipe.transform(new Date(1999, 6, 15), "yyyy-MM-dd")
}

In your template:

<form>
  <div class="form-group">
    <label for="date">Date</label>
    <input
      type="date"
      name="date"
      id="date"
      class="form-control"
      [(ngModel)]="yourForm.date"
    />
  </div>
</form>

type="date" will make it so the format of the date is localized. If your browser is set to a locale where the format is 'dd-MM-yyyy' it will be shown the way you want.

In yout module:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [DatePipe], // <-----
  bootstrap: [AppComponent]
})
Sign up to request clarification or add additional context in comments.

4 Comments

I just made a little project to make sure the code works, cheers. It works just as well when using bootstrap datepicker.
@H3AR7B3A7, the question is about ngb-datepicker
Actually it's the problem with the custom service. If I remove the service then you code do works fine.
The link in eliseo's comment might help... I'll look into it too when I have some more time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.