/
date-picker.component.ts
824 lines (737 loc) · 27.8 KB
/
date-picker.component.ts
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
/**
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
*/
import { Direction, Directionality } from '@angular/cdk/bidi';
import { ESCAPE } from '@angular/cdk/keycodes';
import {
CdkConnectedOverlay,
CdkOverlayOrigin,
ConnectedOverlayPositionChange,
ConnectionPositionPair,
HorizontalConnectionPos,
VerticalConnectionPos
} from '@angular/cdk/overlay';
import { Platform } from '@angular/cdk/platform';
import { DOCUMENT } from '@angular/common';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
forwardRef,
Host,
Inject,
Input,
OnChanges,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
Renderer2,
SimpleChanges,
TemplateRef,
ViewChild,
ViewChildren,
ViewEncapsulation
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { NzResizeObserver } from 'ng-zorro-antd/cdk/resize-observer';
import { slideMotion } from 'ng-zorro-antd/core/animation';
import { NzConfigKey, NzConfigService, WithConfig } from 'ng-zorro-antd/core/config';
import { NzNoAnimationDirective } from 'ng-zorro-antd/core/no-animation';
import { CandyDate, cloneDate, CompatibleValue, wrongSortOrder } from 'ng-zorro-antd/core/time';
import { BooleanInput, FunctionProp, NzSafeAny, OnChangeType, OnTouchedType } from 'ng-zorro-antd/core/types';
import { InputBoolean, toBoolean, valueFunctionProp } from 'ng-zorro-antd/core/util';
import {
DateHelperService,
NzDatePickerI18nInterface,
NzDatePickerLangI18nInterface,
NzI18nService
} from 'ng-zorro-antd/i18n';
import { DatePickerService } from './date-picker.service';
import { DateRangePopupComponent } from './date-range-popup.component';
import {
CompatibleDate,
DisabledTimeFn,
NzDateMode,
PresetRanges,
RangePartType,
SupportTimeOptions
} from './standard-types';
import { PREFIX_CLASS } from './util';
const POPUP_STYLE_PATCH = { position: 'relative' }; // Aim to override antd's style to support overlay's position strategy (position:absolute will cause it not working because the overlay can't get the height/width of it's content)
const NZ_CONFIG_MODULE_NAME: NzConfigKey = 'datePicker';
export type NzDatePickerSizeType = 'large' | 'default' | 'small';
/**
* The base picker for all common APIs
*/
@Component({
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'nz-date-picker,nz-week-picker,nz-month-picker,nz-year-picker,nz-range-picker',
exportAs: 'nzDatePicker',
template: `
<ng-container *ngIf="!nzInline; else inlineMode">
<!-- Content of single picker -->
<div *ngIf="!isRange" class="{{ prefixCls }}-input">
<input
#pickerInput
[attr.id]="nzId"
[class.ant-input-disabled]="nzDisabled"
[disabled]="nzDisabled"
[readOnly]="nzInputReadOnly"
[(ngModel)]="inputValue"
placeholder="{{ getPlaceholder() }}"
[size]="inputSize"
(focus)="onFocus($event)"
(focusout)="onFocusout($event)"
(ngModelChange)="onInputChange($event)"
(keyup.enter)="onKeyupEnter($event)"
/>
<ng-container *ngTemplateOutlet="tplRightRest"></ng-container>
</div>
<!-- Content of range picker -->
<ng-container *ngIf="isRange">
<div class="{{ prefixCls }}-input">
<ng-container *ngTemplateOutlet="tplRangeInput; context: { partType: 'left' }"></ng-container>
</div>
<div #separatorElement class="{{ prefixCls }}-range-separator">
<span class="{{ prefixCls }}-separator">
<ng-container *ngIf="nzSeparator; else defaultSeparator">{{ nzSeparator }}</ng-container>
</span>
<ng-template #defaultSeparator>
<i nz-icon nzType="swap-right" nzTheme="outline"></i>
</ng-template>
</div>
<div class="{{ prefixCls }}-input">
<ng-container *ngTemplateOutlet="tplRangeInput; context: { partType: 'right' }"></ng-container>
</div>
<ng-container *ngTemplateOutlet="tplRightRest"></ng-container>
</ng-container>
</ng-container>
<!-- Input for Range ONLY -->
<ng-template #tplRangeInput let-partType="partType">
<input
#rangePickerInput
[attr.id]="nzId"
[disabled]="nzDisabled"
[readOnly]="nzInputReadOnly"
[size]="inputSize"
(click)="onClickInputBox($event)"
(focusout)="onFocusout($event)"
(focus)="onFocus($event, partType)"
(keyup.enter)="onKeyupEnter($event)"
[(ngModel)]="inputValue[datePickerService.getActiveIndex(partType)]"
(ngModelChange)="onInputChange($event)"
placeholder="{{ getPlaceholder(partType) }}"
/>
</ng-template>
<!-- Right operator icons -->
<ng-template #tplRightRest>
<div class="{{ prefixCls }}-active-bar" [ngStyle]="activeBarStyle"></div>
<span *ngIf="showClear()" class="{{ prefixCls }}-clear" (click)="onClickClear($event)">
<i nz-icon nzType="close-circle" nzTheme="fill"></i>
</span>
<span class="{{ prefixCls }}-suffix">
<ng-container *nzStringTemplateOutlet="nzSuffixIcon; let suffixIcon">
<i nz-icon [nzType]="suffixIcon"></i>
</ng-container>
</span>
</ng-template>
<ng-template #inlineMode>
<div
class="{{ prefixCls }}-dropdown {{ nzDropdownClassName }}"
[class.ant-picker-dropdown-rtl]="dir === 'rtl'"
[class.ant-picker-dropdown-placement-bottomLeft]="currentPositionY === 'bottom' && currentPositionX === 'start'"
[class.ant-picker-dropdown-placement-topLeft]="currentPositionY === 'top' && currentPositionX === 'start'"
[class.ant-picker-dropdown-placement-bottomRight]="currentPositionY === 'bottom' && currentPositionX === 'end'"
[class.ant-picker-dropdown-placement-topRight]="currentPositionY === 'top' && currentPositionX === 'end'"
[class.ant-picker-dropdown-range]="isRange"
[class.ant-picker-active-left]="datePickerService.activeInput === 'left'"
[class.ant-picker-active-right]="datePickerService.activeInput === 'right'"
[ngStyle]="nzPopupStyle"
>
<date-range-popup
[isRange]="isRange"
[inline]="nzInline"
[defaultPickerValue]="nzDefaultPickerValue"
[showWeek]="nzMode === 'week'"
[panelMode]="panelMode"
(panelModeChange)="onPanelModeChange($event)"
(calendarChange)="onCalendarChange($event)"
[locale]="nzLocale?.lang!"
[showToday]="nzMode === 'date' && nzShowToday && !isRange && !nzShowTime"
[showNow]="nzMode === 'date' && nzShowNow && !isRange && !!nzShowTime"
[showTime]="nzShowTime"
[dateRender]="nzDateRender"
[disabledDate]="nzDisabledDate"
[disabledTime]="nzDisabledTime"
[extraFooter]="extraFooter"
[ranges]="nzRanges"
[dir]="dir"
(resultOk)="onResultOk()"
></date-range-popup>
</div>
</ng-template>
<!-- Overlay -->
<ng-template
cdkConnectedOverlay
nzConnectedOverlay
[cdkConnectedOverlayHasBackdrop]="nzBackdrop"
[cdkConnectedOverlayOrigin]="origin"
[cdkConnectedOverlayOpen]="realOpenState"
[cdkConnectedOverlayPositions]="overlayPositions"
[cdkConnectedOverlayTransformOriginOn]="'.ant-picker-wrapper'"
(positionChange)="onPositionChange($event)"
(detach)="close()"
(overlayKeydown)="onOverlayKeydown($event)"
>
<div
class="ant-picker-wrapper"
[nzNoAnimation]="!!noAnimation?.nzNoAnimation"
[@slideMotion]="'enter'"
style="position: relative;"
>
<ng-container *ngTemplateOutlet="inlineMode"></ng-container>
</div>
</ng-template>
`,
host: {
'[class.ant-picker]': `true`,
'[class.ant-picker-range]': `isRange`,
'[class.ant-picker-large]': `nzSize === 'large'`,
'[class.ant-picker-small]': `nzSize === 'small'`,
'[class.ant-picker-disabled]': `nzDisabled`,
'[class.ant-picker-rtl]': `dir === 'rtl'`,
'[class.ant-picker-borderless]': `nzBorderless`,
'[class.ant-picker-inline]': `nzInline`,
'(click)': 'onClickInputBox($event)'
},
providers: [
DatePickerService,
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => NzDatePickerComponent)
}
],
animations: [slideMotion]
})
export class NzDatePickerComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit, ControlValueAccessor {
readonly _nzModuleName: NzConfigKey = NZ_CONFIG_MODULE_NAME;
static ngAcceptInputType_nzAllowClear: BooleanInput;
static ngAcceptInputType_nzAutoFocus: BooleanInput;
static ngAcceptInputType_nzDisabled: BooleanInput;
static ngAcceptInputType_nzBorderless: BooleanInput;
static ngAcceptInputType_nzInputReadOnly: BooleanInput;
static ngAcceptInputType_nzInline: BooleanInput;
static ngAcceptInputType_nzOpen: BooleanInput;
static ngAcceptInputType_nzShowToday: BooleanInput;
static ngAcceptInputType_nzShowNow: BooleanInput;
static ngAcceptInputType_nzMode: NzDateMode | NzDateMode[] | string | string[] | null | undefined;
static ngAcceptInputType_nzShowTime: BooleanInput | SupportTimeOptions | null | undefined;
isRange: boolean = false; // Indicate whether the value is a range value
extraFooter?: TemplateRef<NzSafeAny> | string;
dir: Direction = 'ltr';
public panelMode: NzDateMode | NzDateMode[] = 'date';
private destroyed$: Subject<void> = new Subject();
private isCustomPlaceHolder: boolean = false;
private isCustomFormat: boolean = false;
private showTime: SupportTimeOptions | boolean = false;
// --- Common API
@Input() @InputBoolean() nzAllowClear: boolean = true;
@Input() @InputBoolean() nzAutoFocus: boolean = false;
@Input() @InputBoolean() nzDisabled: boolean = false;
@Input() @InputBoolean() nzBorderless: boolean = false;
@Input() @InputBoolean() nzInputReadOnly: boolean = false;
@Input() @InputBoolean() nzInline: boolean = false;
@Input() @InputBoolean() nzOpen?: boolean;
@Input() nzDisabledDate?: (d: Date) => boolean;
@Input() nzLocale!: NzDatePickerI18nInterface;
@Input() nzPlaceHolder: string | string[] = '';
@Input() nzPopupStyle: object = POPUP_STYLE_PATCH;
@Input() nzDropdownClassName?: string;
@Input() nzSize: NzDatePickerSizeType = 'default';
@Input() nzFormat!: string;
@Input() nzDateRender?: TemplateRef<NzSafeAny> | string | FunctionProp<TemplateRef<Date> | string>;
@Input() nzDisabledTime?: DisabledTimeFn;
@Input() nzRenderExtraFooter?: TemplateRef<NzSafeAny> | string | FunctionProp<TemplateRef<NzSafeAny> | string>;
@Input() @InputBoolean() nzShowToday: boolean = true;
@Input() nzMode: NzDateMode = 'date';
@Input() @InputBoolean() nzShowNow: boolean = true;
@Input() nzRanges?: PresetRanges;
@Input() nzDefaultPickerValue: CompatibleDate | null = null;
@Input() @WithConfig() nzSeparator?: string = undefined;
@Input() @WithConfig() nzSuffixIcon: string | TemplateRef<NzSafeAny> = 'calendar';
@Input() @WithConfig() nzBackdrop = false;
@Input() nzId: string | null = null;
// TODO(@wenqi73) The PanelMode need named for each pickers and export
@Output() readonly nzOnPanelChange = new EventEmitter<NzDateMode | NzDateMode[] | string | string[]>();
@Output() readonly nzOnCalendarChange = new EventEmitter<Array<Date | null>>();
@Output() readonly nzOnOk = new EventEmitter<CompatibleDate | null>();
@Output() readonly nzOnOpenChange = new EventEmitter<boolean>();
@Input() get nzShowTime(): SupportTimeOptions | boolean {
return this.showTime;
}
set nzShowTime(value: SupportTimeOptions | boolean) {
this.showTime = typeof value === 'object' ? value : toBoolean(value);
}
// ------------------------------------------------------------------------
// Input API Start
// ------------------------------------------------------------------------
@ViewChild(CdkConnectedOverlay, { static: false }) cdkConnectedOverlay?: CdkConnectedOverlay;
@ViewChild(DateRangePopupComponent, { static: false }) panel!: DateRangePopupComponent;
@ViewChild('separatorElement', { static: false }) separatorElement?: ElementRef;
@ViewChild('pickerInput', { static: false }) pickerInput?: ElementRef<HTMLInputElement>;
@ViewChildren('rangePickerInput') rangePickerInputs?: QueryList<ElementRef<HTMLInputElement>>;
origin: CdkOverlayOrigin;
document: Document;
inputSize: number = 12;
inputWidth?: number;
prefixCls = PREFIX_CLASS;
inputValue!: NzSafeAny;
activeBarStyle: object = {};
overlayOpen: boolean = false; // Available when "nzOpen" = undefined
overlayPositions: ConnectionPositionPair[] = [
{
offsetY: 2,
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
offsetY: -2,
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
offsetY: 2,
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
},
{
offsetY: -2,
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
}
] as ConnectionPositionPair[];
currentPositionX: HorizontalConnectionPos = 'start';
currentPositionY: VerticalConnectionPos = 'bottom';
get realOpenState(): boolean {
// The value that really decide the open state of overlay
return this.isOpenHandledByUser() ? !!this.nzOpen : this.overlayOpen;
}
ngAfterViewInit(): void {
if (this.nzAutoFocus) {
this.focus();
}
if (this.isRange && this.platform.isBrowser) {
this.nzResizeObserver
.observe(this.elementRef)
.pipe(takeUntil(this.destroyed$))
.subscribe(() => {
this.updateInputWidthAndArrowLeft();
});
}
this.datePickerService.inputPartChange$.pipe(takeUntil(this.destroyed$)).subscribe(partType => {
if (partType) {
this.datePickerService.activeInput = partType;
}
this.focus();
this.updateInputWidthAndArrowLeft();
});
}
updateInputWidthAndArrowLeft(): void {
this.inputWidth = this.rangePickerInputs?.first?.nativeElement.offsetWidth || 0;
const baseStyle = { position: 'absolute', width: `${this.inputWidth}px` };
this.datePickerService.arrowLeft =
this.datePickerService.activeInput === 'left'
? 0
: this.inputWidth + this.separatorElement?.nativeElement.offsetWidth || 0;
if (this.dir === 'rtl') {
this.activeBarStyle = { ...baseStyle, right: `${this.datePickerService.arrowLeft}px` };
} else {
this.activeBarStyle = { ...baseStyle, left: `${this.datePickerService.arrowLeft}px` };
}
this.cdr.markForCheck();
}
getInput(partType?: RangePartType): HTMLInputElement | undefined {
if (this.nzInline) {
return undefined;
}
return this.isRange
? partType === 'left'
? this.rangePickerInputs?.first.nativeElement
: this.rangePickerInputs?.last.nativeElement
: this.pickerInput!.nativeElement;
}
focus(): void {
const activeInputElement = this.getInput(this.datePickerService.activeInput);
if (this.document.activeElement !== activeInputElement) {
activeInputElement?.focus();
}
}
onFocus(event: FocusEvent, partType?: RangePartType): void {
event.preventDefault();
if (partType) {
this.datePickerService.inputPartChange$.next(partType);
}
this.renderClass(true);
}
// blur event has not the relatedTarget in IE11, use focusout instead.
onFocusout(event: FocusEvent): void {
event.preventDefault();
if (!this.elementRef.nativeElement.contains(event.relatedTarget)) {
this.checkAndClose();
}
this.renderClass(false);
}
// Show overlay content
open(): void {
if (this.nzInline) {
return;
}
if (!this.realOpenState && !this.nzDisabled) {
this.updateInputWidthAndArrowLeft();
this.overlayOpen = true;
this.nzOnOpenChange.emit(true);
this.cdr.markForCheck();
}
}
close(): void {
if (this.nzInline) {
return;
}
if (this.realOpenState) {
this.overlayOpen = false;
this.nzOnOpenChange.emit(false);
}
}
showClear(): boolean {
return !this.nzDisabled && !this.isEmptyValue(this.datePickerService.value) && this.nzAllowClear;
}
checkAndClose(): void {
if (!this.realOpenState) {
return;
}
if (this.panel.isAllowed(this.datePickerService.value!, true)) {
if (Array.isArray(this.datePickerService.value) && wrongSortOrder(this.datePickerService.value)) {
const index = this.datePickerService.getActiveIndex();
const value = this.datePickerService.value[index];
this.panel.changeValueFromSelect(value!, true);
return;
}
this.updateInputValue();
this.datePickerService.emitValue$.next();
} else {
this.datePickerService.setValue(this.datePickerService.initialValue!);
this.close();
}
}
onClickInputBox(event: MouseEvent): void {
event.stopPropagation();
this.focus();
if (!this.isOpenHandledByUser()) {
this.open();
}
}
onOverlayKeydown(event: KeyboardEvent): void {
if (event.keyCode === ESCAPE) {
this.datePickerService.initValue();
}
}
// NOTE: A issue here, the first time position change, the animation will not be triggered.
// Because the overlay's "positionChange" event is emitted after the content's full shown up.
// All other components like "nz-dropdown" which depends on overlay also has the same issue.
// See: https://github.com/NG-ZORRO/ng-zorro-antd/issues/1429
onPositionChange(position: ConnectedOverlayPositionChange): void {
this.currentPositionX = position.connectionPair.originX;
this.currentPositionY = position.connectionPair.originY;
this.cdr.detectChanges(); // Take side-effects to position styles
}
onClickClear(event: MouseEvent): void {
event.preventDefault();
event.stopPropagation();
this.datePickerService.initValue(true);
this.datePickerService.emitValue$.next();
}
updateInputValue(): void {
const newValue = this.datePickerService.value;
if (this.isRange) {
this.inputValue = newValue ? (newValue as CandyDate[]).map(v => this.formatValue(v)) : ['', ''];
} else {
this.inputValue = this.formatValue(newValue as CandyDate);
}
this.cdr.markForCheck();
}
formatValue(value: CandyDate): string {
return this.dateHelper.format(value && (value as CandyDate).nativeDate, this.nzFormat);
}
onInputChange(value: string, isEnter: boolean = false): void {
/**
* in IE11 focus/blur will trigger ngModelChange if placeholder changes,
* so we forbidden IE11 to open panel through input change
*/
if (
!this.platform.TRIDENT &&
this.document.activeElement === this.getInput(this.datePickerService.activeInput) &&
!this.realOpenState
) {
this.open();
return;
}
const date = this.checkValidDate(value);
// Can only change date when it's open
if (date && this.realOpenState) {
this.panel.changeValueFromSelect(date, isEnter);
}
}
onKeyupEnter(event: Event): void {
this.onInputChange((event.target as HTMLInputElement).value, true);
}
private checkValidDate(value: string): CandyDate | null {
const date = new CandyDate(this.dateHelper.parseDate(value, this.nzFormat));
if (!date.isValid() || value !== this.dateHelper.format(date.nativeDate, this.nzFormat)) {
return null;
}
return date;
}
getPlaceholder(partType?: RangePartType): string {
return this.isRange
? this.nzPlaceHolder[this.datePickerService.getActiveIndex(partType!)]
: (this.nzPlaceHolder as string);
}
isEmptyValue(value: CompatibleValue): boolean {
if (value === null) {
return true;
} else if (this.isRange) {
return !value || !Array.isArray(value) || value.every(val => !val);
} else {
return !value;
}
}
// Whether open state is permanently controlled by user himself
isOpenHandledByUser(): boolean {
return this.nzOpen !== undefined;
}
// ------------------------------------------------------------------------
// Input API End
// ------------------------------------------------------------------------
constructor(
public nzConfigService: NzConfigService,
public datePickerService: DatePickerService,
protected i18n: NzI18nService,
protected cdr: ChangeDetectorRef,
private renderer: Renderer2,
private elementRef: ElementRef,
private dateHelper: DateHelperService,
private nzResizeObserver: NzResizeObserver,
private platform: Platform,
@Inject(DOCUMENT) doc: NzSafeAny,
@Optional() private directionality: Directionality,
@Host() @Optional() public noAnimation?: NzNoAnimationDirective
) {
this.document = doc;
this.origin = new CdkOverlayOrigin(this.elementRef);
}
ngOnInit(): void {
// Subscribe the every locale change if the nzLocale is not handled by user
if (!this.nzLocale) {
this.i18n.localeChange.pipe(takeUntil(this.destroyed$)).subscribe(() => this.setLocale());
}
// Default value
this.datePickerService.isRange = this.isRange;
this.datePickerService.initValue(true);
this.datePickerService.emitValue$.pipe(takeUntil(this.destroyed$)).subscribe(_ => {
const value = this.datePickerService.value;
this.datePickerService.initialValue = cloneDate(value);
if (this.isRange) {
const vAsRange = value as CandyDate[];
if (vAsRange.length) {
this.onChangeFn([vAsRange[0]?.nativeDate ?? null, vAsRange[1]?.nativeDate ?? null]);
} else {
this.onChangeFn([]);
}
} else {
if (value) {
this.onChangeFn((value as CandyDate).nativeDate);
} else {
this.onChangeFn(null);
}
}
this.onTouchedFn();
// When value emitted, overlay will be closed
this.close();
});
this.directionality.change?.pipe(takeUntil(this.destroyed$)).subscribe((direction: Direction) => {
this.dir = direction;
this.cdr.detectChanges();
});
this.dir = this.directionality.value;
this.inputValue = this.isRange ? ['', ''] : '';
this.setModeAndFormat();
this.datePickerService.valueChange$.pipe(takeUntil(this.destroyed$)).subscribe(() => {
this.updateInputValue();
});
}
ngOnChanges(changes: SimpleChanges): void {
if (changes.nzPopupStyle) {
// Always assign the popup style patch
this.nzPopupStyle = this.nzPopupStyle ? { ...this.nzPopupStyle, ...POPUP_STYLE_PATCH } : POPUP_STYLE_PATCH;
}
// Mark as customized placeholder by user once nzPlaceHolder assigned at the first time
if (changes.nzPlaceHolder?.currentValue) {
this.isCustomPlaceHolder = true;
}
if (changes.nzFormat?.currentValue) {
this.isCustomFormat = true;
}
if (changes.nzLocale) {
// The nzLocale is currently handled by user
this.setDefaultPlaceHolder();
}
if (changes.nzRenderExtraFooter) {
this.extraFooter = valueFunctionProp(this.nzRenderExtraFooter!);
}
if (changes.nzMode) {
this.setDefaultPlaceHolder();
this.setModeAndFormat();
}
}
ngOnDestroy(): void {
this.destroyed$.next();
this.destroyed$.complete();
}
setModeAndFormat(): void {
const inputFormats: { [key in NzDateMode]?: string } = {
year: 'yyyy',
month: 'yyyy-MM',
week: this.i18n.getDateLocale() ? 'RRRR-II' : 'yyyy-ww', // Format for week
date: this.nzShowTime ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd'
};
if (!this.nzMode) {
this.nzMode = 'date';
}
this.panelMode = this.isRange ? [this.nzMode, this.nzMode] : this.nzMode;
// Default format when it's empty
if (!this.isCustomFormat) {
this.nzFormat = inputFormats[this.nzMode as NzDateMode]!;
}
this.inputSize = Math.max(10, this.nzFormat.length) + 2;
this.updateInputValue();
}
/**
* Triggered when overlayOpen changes (different with realOpenState)
*
* @param open The overlayOpen in picker component
*/
onOpenChange(open: boolean): void {
this.nzOnOpenChange.emit(open);
}
// ------------------------------------------------------------------------
// | Control value accessor implements
// ------------------------------------------------------------------------
// NOTE: onChangeFn/onTouchedFn will not be assigned if user not use as ngModel
onChangeFn: OnChangeType = () => void 0;
onTouchedFn: OnTouchedType = () => void 0;
writeValue(value: CompatibleDate): void {
this.setValue(value);
this.cdr.markForCheck();
}
registerOnChange(fn: OnChangeType): void {
this.onChangeFn = fn;
}
registerOnTouched(fn: OnTouchedType): void {
this.onTouchedFn = fn;
}
setDisabledState(isDisabled: boolean): void {
this.nzDisabled = isDisabled;
this.cdr.markForCheck();
}
// ------------------------------------------------------------------------
// | Internal methods
// ------------------------------------------------------------------------
// Reload locale from i18n with side effects
private setLocale(): void {
this.nzLocale = this.i18n.getLocaleData('DatePicker', {});
this.setDefaultPlaceHolder();
this.cdr.markForCheck();
}
private setDefaultPlaceHolder(): void {
if (!this.isCustomPlaceHolder && this.nzLocale) {
const defaultPlaceholder: { [key in NzDateMode]?: string } = {
year: this.getPropertyOfLocale('yearPlaceholder'),
month: this.getPropertyOfLocale('monthPlaceholder'),
week: this.getPropertyOfLocale('weekPlaceholder'),
date: this.getPropertyOfLocale('placeholder')
};
const defaultRangePlaceholder: { [key in NzDateMode]?: string[] } = {
year: this.getPropertyOfLocale('rangeYearPlaceholder'),
month: this.getPropertyOfLocale('rangeMonthPlaceholder'),
week: this.getPropertyOfLocale('rangeWeekPlaceholder'),
date: this.getPropertyOfLocale('rangePlaceholder')
};
this.nzPlaceHolder = this.isRange
? defaultRangePlaceholder[this.nzMode as NzDateMode]!
: defaultPlaceholder[this.nzMode as NzDateMode]!;
}
}
private getPropertyOfLocale<T extends keyof NzDatePickerLangI18nInterface>(
type: T
): NzDatePickerLangI18nInterface[T] {
return this.nzLocale.lang[type] || this.i18n.getLocaleData(`DatePicker.lang.${type}`);
}
// Safe way of setting value with default
private setValue(value: CompatibleDate): void {
const newValue: CompatibleValue = this.datePickerService.makeValue(value);
this.datePickerService.setValue(newValue);
this.datePickerService.initialValue = newValue;
}
renderClass(value: boolean): void {
// TODO: avoid autoFocus cause change after checked error
if (value) {
this.renderer.addClass(this.elementRef.nativeElement, 'ant-picker-focused');
} else {
this.renderer.removeClass(this.elementRef.nativeElement, 'ant-picker-focused');
}
}
onPanelModeChange(panelMode: NzDateMode | NzDateMode[]): void {
this.nzOnPanelChange.emit(panelMode);
}
// Emit nzOnCalendarChange when select date by nz-range-picker
onCalendarChange(value: CompatibleValue): void {
if (this.isRange && Array.isArray(value)) {
const rangeValue = value.filter(x => x instanceof CandyDate).map(x => x!.nativeDate);
this.nzOnCalendarChange.emit(rangeValue);
}
}
onResultOk(): void {
if (this.isRange) {
const value = this.datePickerService.value as CandyDate[];
if (value.length) {
this.nzOnOk.emit([value[0]?.nativeDate || null, value[1]?.nativeDate || null]);
} else {
this.nzOnOk.emit([]);
}
} else {
if (this.datePickerService.value) {
this.nzOnOk.emit((this.datePickerService.value as CandyDate).nativeDate);
} else {
this.nzOnOk.emit(null);
}
}
}
}