0

我環顧四周,無法找到任何明確的這個 - 你可以使用ng2-bootstrap datepicker與Angular2模型驅動的形式,還是隻能使用模板形式?模型驅動的形式與ng2-bootstrap datepicker

的文檔描述的選擇,這樣你會如下(作爲一個例子)使用它:

<datepicker [(ngModel)]="startDate" ></datepicker> 

...這似乎工作。理想情況下,我想這樣使用它:

<datepicker formControlName="startDate" ></datepicker> 

...但它似乎並沒有開箱即用。有沒有辦法使用這個模塊與模型驅動的形式?如果沒有,是否有一個合理的替代方案可以與模型驅動的表單一起使用? (我也嘗試過ng2-datepicker,但是有一個outstanding bug,這使得使用SystemJS很不方便,這很不幸,因爲它看起來很光滑)。

+0

當你使用第一個例子時會發生什麼?你有錯誤嗎?我從來沒有使用這個庫,但我認爲用ngModel和模板形式,你需要一個'name'屬性 –

+0

它工作正常,你不需要'name'屬性。 ...所以如果我使用模板驅動的表單,我會全部設置,但我更喜歡模型驅動的表單。 – WillyC

+0

對不起,我誤解了你的問題。我讀它是因爲你試圖使用第一個例子,而不是第二個例子。 Ooops :-D –

回答

1

我已經使用了primeNg控件集,他們有一個令人驚歎的功能的日曆控件。在這裏看到: PrimeNg Calendar UI Control

+0

看起來非常棒!謝謝 - 我會給你一個鏡頭。這將是datepicker#4我尋求datepicker烏托邦但它肯定看起來很有前途。我不知道爲什麼在我的搜索中沒有顯示出更突出的位置... – WillyC

+0

如果它適合您,請標記爲答案。我在我的應用程序中使用日曆控件。你可能沒有找到它,因爲它不是一個日期選擇器,而是一個日曆,儘管它有一個構建datepicker的功能。 –

+0

會做 - 今天下午我會弄明白的。目前看起來不錯。 – WillyC

4

我做了簡單的包裝ng2-bootstrap datepicker使用它與ReactiveFormsModule。它使用時刻,所以你可以根據你的需要改進它。

Live demo

定製datepicker.component.ts

import { Component, forwardRef, Provider } from '@angular/core'; 
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; 
import * as moment from 'moment'; 

let DATEPICKER_VALUE_ACCESSOR: Provider = { 
    provide: NG_VALUE_ACCESSOR, 
    useExisting: forwardRef(() => CustomDatepickerComponent), 
    multi: true 
}; 

@Component({ 
    selector: 'custom-datepicker[formControlName]', 
    template: ` 
    <datepicker [(ngModel)]="datePickerValue"></datepicker> 
    `, 
    providers: [DATEPICKER_VALUE_ACCESSOR] 
}) 
export class CustomDatepickerComponent implements ControlValueAccessor { 
    change = (_: any) => {}; 
    _customDatePickerValue; 
    _datePickerValue: Date; 

    get customDatePickerValue() { 
    return this._customDatepickerValue; 
    } 
    set customDatePickerValue(value) { 
    this._customDatepickerValue = value; 
    this.change(value); 
    } 

    get datePickerValue() { 
    return this._datePickerValue; 
    } 
    set datePickerValue(value) { 
    this._datePickerValue = value; 
    this.customDatePickerValue = moment(value).format('DD/MM/YYYY'); 
    } 

    writeValue() {} 
    registerOnChange(fn) { 
    this.change = fn; 
    } 
    registerOnTouched() {} 
} 

使用在你的組件

app.component.ts

import { Component } from '@angular/core'; 
import { FormGroup, FormControl } from '@angular/forms'; 

@Component({ 
    selector: 'my-app', 
    template: ` 
    <form [formGroup]="form"> 
    <custom-datepicker formControlName="customDatepickerValue"></custom-datepicker> 
    </form> 

    <pre>{{form.value | json }}</pre> 
    ` 
}) 
export class AppComponent { 
    form: FormGroup = new FormGroup({ 
    customDatepickerValue: new FormControl() 
    }) 
}