【问题标题】:Angular Bootstrap Datepicker not bindingAngular Bootstrap Datepicker 不绑定
【发布时间】:2021-08-12 22:23:26
【问题描述】:

我正在尝试使用日期选择器,但它似乎没有显示在输入控件中。数据可以正确返回,因为我可以将其输出到屏幕上并查看。

Angular 版本:“@angular/core”:“~11.2.11”
引导版本: "@ng-bootstrap/ng-bootstrap": "^10.0.0", “引导程序”:“^4.6.0”

正在返回的数据(日期):

“2020-10-21T09:39:04.357”

我想只输出月、日和年。

即使我返回的字符串“2016-05-10”也不显示。

如果我从日历中选择一个日期,它会正确更新我的模型。它显示为:

{ "年": 2021, "月": 8, "日": 12 }

我尝试声明一个变量并绑定到该变量,但它也不起作用。我的变量是:

bsValue = new Date();
<div class="input-group">
  <input class="form-control" placeholder="yyyy-mm-dd"
      name="lastActivityDate" [(ngModel)]="user.lastActivityDate"
      ngbDatepicker #d2="ngbDatepicker">
  <div class="input-group-append">
    <div class="input-group-text" (click)="d2.toggle()">
      <i class="fa fa-calendar" style="cursor: pointer;"></i>
    </div>
  </div>
</div>

【问题讨论】:

    标签: angular ng-bootstrap ngb-datepicker


    【解决方案1】:

    在您的组件中将 DatePipe 添加到构造函数并初始化您的日期:

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

    在您的模板中:

    <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" 将使日期格式本地化。如果您的浏览器设置为格式为“dd-MM-yyyy”的区域设置,它将以您想要的方式显示。

    在你的模块中:

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule
      ],
      providers: [DatePipe], // <-----
      bootstrap: [AppComponent]
    })
    

    【讨论】:

      【解决方案2】:

      根据NG-Bootstrap DatePicker Date model and format

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

      因此您需要将日期字符串转换为NgbDateStructNgbDate 类型以绑定到[(ngModel)]


      解决方案 1:将日期字符串转换为 NgbDateNgbDate 类型。

      转换为NgbDate 类型

      import { NgbDate } from '@ng-bootstrap/ng-bootstrap';
      
      let date = new Date("2020-10-21T09:39:04.357");
      let dateModel: NgbDate = new NgbDate(
        date.getFullYear(),
        date.getMonth() + 1,
        date.getDate())
      );
      

      转换为NgbDateStruct 类型

      import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap';
      
      let date = new Date("2020-10-21T09:39:04.357");
      let dateModel: NgbDateStruct =  {
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate()
      };
      

      Sample Solution 1 on StackBlitz


      解决方案 2:应用自定义日期适配器

      自定义日期适配器允许使用自定义日期字符串格式将日期字符串绑定到 [(ngModel)]

      date.adapter.ts

      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 = new Date(value);
            return {
              day: date.getDate(),
              month: date.getMonth() + 1,
              year: date.getFullYear()
            };
          }
          return null;
        }
      
        toModel(date: NgbDateStruct | null): string | null {
          if (date) {
            let dateObj = new Date(date.year, date.month - 1, date.day);
            return dateObj.toISOString();
          }
      
          return 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 = new Date(value);
            return {
              day: date.getDate(),
              month: date.getMonth() + 1,
              year: date.getFullYear()
            };
          }
          return null;
        }
      
        format(date: NgbDateStruct | null): string {
          return date
            ? date.day + this.DELIMITER + date.month + this.DELIMITER + date.year
            : '';
        }
      }
      

      app.module.ts

      import {
        NgbDateAdapter,
        NgbDateParserFormatter,
        NgbModule
      } from '@ng-bootstrap/ng-bootstrap';
      import { CustomAdapter, CustomDateParserFormatter } from './datepicker-adapter';
      
      @NgModule({
        ...
        providers: [
          { provide: NgbDateAdapter, useClass: CustomAdapter },
          { provide: NgbDateParserFormatter, useClass: CustomDateParserFormatter }
        ]
      })
      export class AppModule {}
      

      Sample Solution 2 on StackBlitz


      参考文献

      Custom date adapter and formatter

      【讨论】:

        猜你喜欢
        • 2018-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-03
        • 1970-01-01
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多