2

我有一个输入,我想用 Angular 2 Bootstrap 日期选择器填充它。当页面打开时,该值通过使用以今天的日期开始value="{{ getStartDate() | date:'fullDate'}}"。但是当我单击按钮并打开日期选择器并选择一个新日期时,该值不会填充输入。我也不能再点击按钮来关闭日期选择器。

HTML:

<form class="form-inline">
<div>
<div class="form-group" [ngClass]="{'has-error':!secondForm.controls['startDate'].valid && secondForm.controls['startDate'].touched}">
  <input value="{{ getStartDate() | date:'fullDate'}}" style="width:250px" class="form-control" type="text" [formControl]="secondForm.controls['startDate']">
</div>
<div style="display:inline-block">
  <ngb-datepicker *ngIf="startCheck==true;" [(ngModel)]="dt" class="dropdown-toggle" [ngModelOptions]="{standalone: true}" style="position:absolute; z-index:1"></ngb-datepicker>
</div>
<button type="button" class="btn icon-calendar" (click)="showDatePick()"></button>
<button type="button" class="btn icon-search" [disabled]="!secondForm.valid"></button>
 </div>
 </form>

打字稿:

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {NgbDateStruct} from '@ng-bootstrap/ng-bootstrap';

@Component({
selector: 'calendar-pick',
styleUrls: ['../app.component.css'],
templateUrl: './calendarpick.component.html'
})

export class CalendarPickComponent {
public dt:Date = new Date();
public startCheck: boolean = false;
//Might need to change this to complexForm, not sure yet
secondForm : FormGroup;

public constructor(fb: FormBuilder) {
this.secondForm = fb.group({
  'startDate' : [this.dt, Validators.required]
})
this.secondForm.valueChanges.subscribe( (form: any) => {
    console.log('form changed to:', form);
  }
);
}

public getStartDate():number {
return this.dt && this.dt.getTime() || new Date().getTime();
}

public showDatePick():void {
if (this.startCheck == false){
  this.startCheck = true;
} else {
  this.startCheck = false;
}
}
}
4

1 回答 1

4

ng-bootstrap datepicker 的模型不是 Date() 对象,它是一个 NgbDateStruct,它由 {month, day, year}

为了获得所需的行为,代码如下所示:

import {DatePipe} from "@angular/common";

@Component({providers: [DatePipe]})

public constructor(fb: FormBuilder, private datePipe: DatePipe)
public dt: NgbDateStruct;
<...>
public getStartDate():number {
let timestamp = this.dt != null ? new Date(this.dt.year, this.dt.month-1, this.dt.day).getTime() : new Date().getTime();
this.secondForm.controls['startDate'].setValue(this.datePipe.transform(timestamp, 'fullDate'));
}

标记更改为: <input style="width:250px" [value]="getStartDate()" class="form-control" type="text" [formControl]="secondForm.controls['startDate']">

这是完整的 plunker:https ://plnkr.co/edit/zqGpoJZ1psKmST0S7Ix0?p=preview

请注意,ng-bootstrap 团队的月份索引是基于 0 的,而不是基于 1 的,这在将本机 Date 对象与 NgbDate 结合使用时令人抓狂。

此外,使用默认值 new Date().getTime() 编写它的方式意味着您永远不会有可能/可能不需要的空白值。它总是肮脏而有效的。

于 2016-11-03T17:54:28.163 回答