【问题标题】:Unable to set date to the ng Bootstrap datepicker in Angular无法将日期设置为 Angular 中的 ng Bootstrap 日期选择器
【发布时间】:2020-02-06 11:53:54
【问题描述】:

我在 Angular 中工作,我以反应形式使用 ng Bootstrap Datepicker

我尝试使用补丁值设置 ngBootstrap DatePicker 的值,但无法为其设置值

我正在分享我的代码

HTML

<div class="form-group required control-label">
  <label>Date of Joining</label>
  <!-- <input type="text" class="form-control" formControlName="doj"  placeholder=""/> -->
  <div class="form-group">
    <div class="input-group">
      <input class="form-control"  formControlName="doj" placeholder="yyyy-mm-dd" name="dp" ngbDatepicker
                #e="ngbDatepicker">
      <div class="input-group-append">
        <button class="btn btn-outline-secondary calendar" (click)="e.toggle()" type="button"></button>
      </div>
    </div>
  </div>
</div> 

TS

this.employeeForm.patchValue({
  doj: this.date
})

【问题讨论】:

  • ngbDatePicker 是由具有年、月和日的对象“馈送”(缺陷),所以你可以这样做,例如this.employeeForm.patchValue({doj:{year:2020,month:92;day:06}}) - 或 this.date={year:2020,month:92;day:06};this.employeeForm.patchValue({doj:this.date})。您还可以使用 Adapter 来使用 Javascripts Date 对象,请参阅ng-bootstrap.github.io/#/components/datepicker/…

标签: angular datepicker angular8 ng-bootstrap


【解决方案1】:

ngbDatepicker 使用 NgbDateStruct 接口作为模型,而不是原生 Date 对象。

this.employeeForm.patchValue({
doj : { year: 2020, month: 2, day: 6 } // should be { year , month , date } format
})

或创建自定义解析器格式化程序。

import { NgbDateParserFormatter, NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
import { Injectable } from '@angular/core';
import { isNumber, toInteger, padNumber } from '@ng-bootstrap/ng-bootstrap/util/util';

@Injectable()
export class NgbDateCustomParserFormatter extends NgbDateParserFormatter {
  parse(value: string): NgbDateStruct {
    if (value) {
      const dateParts = value.trim().split('-');
      if (dateParts.length === 1 && isNumber(dateParts[0])) {
        return {day: toInteger(dateParts[0]), month: null, year: null};
      } else if (dateParts.length === 2 && isNumber(dateParts[0]) && isNumber(dateParts[1])) {
        return {day: toInteger(dateParts[0]), month: toInteger(dateParts[1]), year: null};
      } else if (dateParts.length === 3 && isNumber(dateParts[0]) && isNumber(dateParts[1]) && isNumber(dateParts[2])) {
        return {day: toInteger(dateParts[0]), month: toInteger(dateParts[1]), year: toInteger(dateParts[2])};
      }
    }
    return null;
  }

  format(date: NgbDateStruct): string {
    return date ?
        `${isNumber(date.day) ? padNumber(date.day) : ''}-${isNumber(date.month) ? padNumber(date.month) : ''}-${date.year}` :
        '';
  }
}

在@NgModule 中为自定义解析器格式化程序设置提供程序。

providers: [
    {provide: NgbDateParserFormatter, useClass: NgbDateCustomParserFormatter}
   ]

【讨论】:

    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 2020-09-01
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多