Angular DateTimePicker

Angular 日期選擇器,下載安裝,支持最新 Angular 13 版本。

Github

Demo

Install ng2-date-picker

1
npm install ng2-date-picker --save

app.module

1
@NgModule({ ... imports: [ ... DpDatePickerModule ] })

styles

angular.json

1
2
3
4
"styles": [
...
"node_modules/@angular/cdk/overlay-prebuilt.css"
]

Install dayjs

1
npm install dayjs --save

import

app.component

1
2
3
import { Component } from '@angular/core';
import * as dayjs from 'dayjs';
import {DatePickerComponent, IDatePickerConfig} from 'ng2-date-picker';

ViewChild

1
2
3
4
5
6
7
@Component({
....
})
export class AppComponent {

@ViewChild('dayPicker') datePicker!: DatePickerComponent;
...

Config

設定預設

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
datePickerConfig:IDatePickerConfig = {
firstDayOfWeek: 'su',
monthFormat: 'MMM, YYYY',
disableKeypress: false,
allowMultiSelect: false,
closeOnSelect: undefined,
closeOnSelectDelay: 100,
openOnFocus: true,
openOnClick: true,
onOpenDelay: 0,
weekDayFormat: 'ddd',
showNearMonthDays: true,
showWeekNumbers: false,
enableMonthSelector: true,
yearFormat: 'YYYY',
showGoToCurrent: true,
dayBtnFormat: 'DD',
monthBtnFormat: 'MMM',
hours12Format: 'hh',
hours24Format: 'HH',
meridiemFormat: 'A',
minutesFormat: 'mm',
minutesInterval: 1,
secondsFormat: 'ss',
secondsInterval: 1,
showSeconds: false,
showTwentyFourHours: false,
timeSeparator: ':',
multipleYearsNavigateBy: 10,
showMultipleYearsNavigation: false,
hideInputContainer: false,
unSelectOnClick: true,
hideOnOutsideClick: true,
format: "YYYY-MM-DD HH:mm",
min: this.set_Date(),
max: this.set_Date(3),
}
....

onChange

取及時變更的日期

1
2
3
4
5
// Date Time Change
timePickerChange(e:any): void {
const selectDate:any = new Date(e.$d);
console.log(selectDate);
}

min & max

設定日期選擇器,最小日期和最大日期範圍。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Date Time
set_Date(days:number = 0): string {

const d = new Date();

if(days != 0)
{
d.setDate(d.getDate()+days);
}

let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
const hr = d.getHours();
const min = d.getMinutes();

if (month.length < 2)
{
month = '0' + month;
}

if (day.length < 2)
{
day = '0' + day;
}

const datetime:string = [year, month, day].join('-')+' '+hr+':'+min+':00';

return datetime;
}

Locale

1
2
3
4
5
6
7
8
9
ngOnInit(): void {
this.change_Locale();
}

change_Locale(): void {
import(`dayjs/locale/zh-tw`).then(() => {
dayjs.locale('zh-tw');
});
}

Html

1
2
3
<dp-date-picker theme="dp-material" mode="daytime"
[config]="datePickerConfig" placeholder="選擇日期" (onChange)="timePickerChange($event)">
</dp-date-picker>

作者

Nigo Chen

發表於

2022-06-20

更新於

2022-06-20

許可協議

評論