简体   繁体   中英

Unable to set default date in angular bootstrap datepicker control

I am using AngularBootstrap 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)

在此处输入图片说明

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]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM