• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IgniteUI / igniteui-angular / 16781389358

06 Aug 2025 03:29PM UTC coverage: 91.429% (-0.01%) from 91.44%
16781389358

Pull #16121

github

web-flow
Merge 94ea035b9 into 6d3657091
Pull Request #16121: Adding PredefinedRangesArea

13466 of 15813 branches covered (85.16%)

31 of 35 new or added lines in 3 files covered. (88.57%)

2 existing lines in 1 file now uncovered.

27203 of 29753 relevant lines covered (91.43%)

34452.71 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

90.57
/projects/igniteui-angular/src/lib/date-range-picker/date-range-picker.component.ts
1
import {
2
    AfterViewInit, booleanAttribute, ChangeDetectorRef, Component, ContentChild, ContentChildren, ElementRef,
3
    EventEmitter, HostBinding, HostListener, Inject, Injector, Input, LOCALE_ID,
4
    OnChanges, OnDestroy, OnInit, Optional, Output, QueryList,
5
    SimpleChanges, TemplateRef, ViewChild, ViewContainerRef
6
} from '@angular/core';
7
import { NgTemplateOutlet, getLocaleFirstDayOfWeek } from '@angular/common';
8
import {
9
    AbstractControl, ControlValueAccessor, NgControl,
10
    NG_VALIDATORS, NG_VALUE_ACCESSOR, ValidationErrors, Validator
11
} from '@angular/forms';
12

13
import { fromEvent, merge, MonoTypeOperatorFunction, noop, Subscription } from 'rxjs';
14
import { filter, takeUntil } from 'rxjs/operators';
15

16
import { CalendarSelection, IgxCalendarComponent } from '../calendar/public_api';
17
import { DateRangeType } from '../core/dates';
18
import { DateRangePickerResourceStringsEN, IDateRangePickerResourceStrings } from '../core/i18n/date-range-picker-resources';
19
import { IBaseCancelableBrowserEventArgs, isDate, parseDate, PlatformUtil } from '../core/utils';
20
import { IgxCalendarContainerComponent } from '../date-common/calendar-container/calendar-container.component';
21
import { PickerBaseDirective } from '../date-common/picker-base.directive';
22
import { IgxPickerActionsDirective } from '../date-common/picker-icons.common';
23
import { DateTimeUtil } from '../date-common/util/date-time.util';
24
import { IgxOverlayOutletDirective } from '../directives/toggle/toggle.directive';
25
import {
26
    IgxInputDirective, IgxInputGroupComponent, IgxInputGroupType, IgxInputState,
27
    IgxLabelDirective, IGX_INPUT_GROUP_TYPE
28
} from '../input-group/public_api';
29
import {
30
    AutoPositionStrategy, IgxOverlayService, OverlayCancelableEventArgs, OverlayEventArgs,
31
    OverlaySettings, PositionSettings
32
} from '../services/public_api';
33
import { DateRange, IgxDateRangeEndComponent, IgxDateRangeInputsBaseComponent, IgxDateRangeSeparatorDirective, IgxDateRangeStartComponent, DateRangePickerFormatPipe, CustomDateRange } from './date-range-picker-inputs.common';
34
import { IgxPrefixDirective } from '../directives/prefix/prefix.directive';
35
import { IgxIconComponent } from '../icon/icon.component';
36
import { getCurrentResourceStrings } from '../core/i18n/resources';
37
import { fadeIn, fadeOut } from 'igniteui-angular/animations';
38

39
const SingleInputDatesConcatenationString = ' - ';
3✔
40

41
/**
42
 * Provides the ability to select a range of dates from a calendar UI or editable inputs.
43
 *
44
 * @igxModule IgxDateRangeModule
45
 *
46
 * @igxTheme igx-input-group-theme, igx-calendar-theme, igx-date-range-picker-theme
47
 *
48
 * @igxKeywords date, range, date range, date picker
49
 *
50
 * @igxGroup scheduling
51
 *
52
 * @remarks
53
 * It displays the range selection in a single or two input fields.
54
 * The default template displays a single *readonly* input field
55
 * while projecting `igx-date-range-start` and `igx-date-range-end`
56
 * displays two *editable* input fields.
57
 *
58
 * @example
59
 * ```html
60
 * <igx-date-range-picker mode="dropdown"></igx-date-range-picker>
61
 * ```
62
 */
63
@Component({
64
    selector: 'igx-date-range-picker',
65
    templateUrl: './date-range-picker.component.html',
66
    providers: [
67
        { provide: NG_VALUE_ACCESSOR, useExisting: IgxDateRangePickerComponent, multi: true },
68
        { provide: NG_VALIDATORS, useExisting: IgxDateRangePickerComponent, multi: true }
69
    ],
70
    imports: [
71
        NgTemplateOutlet,
72
        IgxIconComponent,
73
        IgxInputGroupComponent,
74
        IgxInputDirective,
75
        IgxPrefixDirective,
76
        DateRangePickerFormatPipe
77
    ]
78
})
79
export class IgxDateRangePickerComponent extends PickerBaseDirective
3✔
80
    implements OnChanges, OnInit, AfterViewInit, OnDestroy, ControlValueAccessor, Validator {
81

82
    /**
83
     * The number of displayed month views.
84
     *
85
     * @remarks
86
     * Default is `2`.
87
     *
88
     * @example
89
     * ```html
90
     * <igx-date-range-picker [displayMonthsCount]="3"></igx-date-range-picker>
91
     * ```
92
     */
93
    @Input()
94
    public displayMonthsCount = 2;
72✔
95

96
    /**
97
     * Gets/Sets whether dates that are not part of the current month will be displayed.
98
     *
99
     * @remarks
100
     * Default value is `false`.
101
     *
102
     * @example
103
     * ```html
104
     * <igx-date-range-picker [hideOutsideDays]="true"></igx-date-range-picker>
105
     * ```
106
     */
107
    @Input({ transform: booleanAttribute })
108
    public hideOutsideDays: boolean;
109

110
    /**
111
     * A custom formatter function, applied on the selected or passed in date.
112
     *
113
     * @example
114
     * ```typescript
115
     * private dayFormatter = new Intl.DateTimeFormat("en", { weekday: "long" });
116
     * private monthFormatter = new Intl.DateTimeFormat("en", { month: "long" });
117
     *
118
     * public formatter(date: Date): string {
119
     *  return `${this.dayFormatter.format(date)} - ${this.monthFormatter.format(date)} - ${date.getFullYear()}`;
120
     * }
121
     * ```
122
     * ```html
123
     * <igx-date-range-picker [formatter]="formatter"></igx-date-range-picker>
124
     * ```
125
     */
126
    @Input()
127
    public formatter: (val: DateRange) => string;
128

129
    /**
130
     * Overrides the default text of the calendar dialog **Done** button.
131
     *
132
     * @remarks
133
     * Defaults to the value from resource strings, `"Done"` for the built-in EN.
134
     * The button will only show up in `dialog` mode.
135
     *
136
     * @example
137
     * ```html
138
     * <igx-date-range-picker doneButtonText="完了"></igx-date-range-picker>
139
     * ```
140
     */
141
    @Input()
142
    public set doneButtonText(value: string) {
143
        this._doneButtonText = value;
1✔
144
    }
145

146
    public get doneButtonText(): string {
147
        if (this._doneButtonText === null) {
6✔
148
            return this.resourceStrings.igx_date_range_picker_done_button;
5✔
149
        }
150
        return this._doneButtonText;
1✔
151
    }
152
    /**
153
     * Custom overlay settings that should be used to display the calendar.
154
     *
155
     * @example
156
     * ```html
157
     * <igx-date-range-picker [overlaySettings]="customOverlaySettings"></igx-date-range-picker>
158
     * ```
159
     */
160
    @Input()
161
    public override overlaySettings: OverlaySettings;
162

163
    /**
164
     * The format used when editable inputs are not focused.
165
     *
166
     * @remarks
167
     * Uses Angular's DatePipe.
168
     *
169
     * @example
170
     * ```html
171
     * <igx-date-range-picker displayFormat="EE/M/yy"></igx-date-range-picker>
172
     * ```
173
     *
174
     */
175
    @Input()
176
    public override displayFormat: string;
177

178
    /**
179
     * The expected user input format and placeholder.
180
     *
181
     * @example
182
     * ```html
183
     * <igx-date-range-picker inputFormat="dd/MM/yy"></igx-date-range-picker>
184
     * ```
185
     */
186
    @Input()
187
    public override inputFormat: string;
188

189
    /**
190
     * The minimum value in a valid range.
191
     *
192
     * @example
193
     * <igx-date-range-picker [minValue]="minDate"></igx-date-range-picker>
194
     */
195
    @Input()
196
    public set minValue(value: Date | string) {
197
        this._minValue = value;
27✔
198
        this.onValidatorChange();
27✔
199
    }
200

201
    public get minValue(): Date | string {
202
        return this._minValue;
102✔
203
    }
204

205
    /**
206
     * The maximum value in a valid range.
207
     *
208
     * @example
209
     * <igx-date-range-picker [maxValue]="maxDate"></igx-date-range-picker>
210
     */
211
    @Input()
212
    public set maxValue(value: Date | string) {
213
        this._maxValue = value;
27✔
214
        this.onValidatorChange();
27✔
215
    }
216

217
    public get maxValue(): Date | string {
218
        return this._maxValue;
102✔
219
    }
220

221
    /**
222
     * An accessor that sets the resource strings.
223
     * By default it uses EN resources.
224
     */
225
    @Input()
226
    public set resourceStrings(value: IDateRangePickerResourceStrings) {
227
        this._resourceStrings = Object.assign({}, this._resourceStrings, value);
×
228
    }
229

230
    /**
231
     * An accessor that returns the resource strings.
232
     */
233
    public get resourceStrings(): IDateRangePickerResourceStrings {
234
        return this._resourceStrings;
79✔
235
    }
236

237
    /**
238
     * Sets the `placeholder` for single-input `IgxDateRangePickerComponent`.
239
     *
240
     *   @example
241
     * ```html
242
     * <igx-date-range-picker [placeholder]="'Choose your dates'"></igx-date-range-picker>
243
     * ```
244
     */
245
    @Input()
246
    public override placeholder = '';
72✔
247

248
    /**
249
     * Gets/Sets the container used for the popup element.
250
     *
251
     * @remarks
252
     *  `outlet` is an instance of `IgxOverlayOutletDirective` or an `ElementRef`.
253
     * @example
254
     * ```html
255
     * <div igxOverlayOutlet #outlet="overlay-outlet"></div>
256
     * //..
257
     * <igx-date-range-picker [outlet]="outlet"></igx-date-range-picker>
258
     * //..
259
     * ```
260
     */
261
    @Input()
262
    public override outlet: IgxOverlayOutletDirective | ElementRef<any>;
263

264
    /**
265
     * Show/hide week numbers
266
     *
267
     * @remarks
268
     * Default is `false`.
269
     *
270
     * @example
271
     * ```html
272
     * <igx-date-range-picker [showWeekNumbers]="true"></igx-date-range-picker>
273
     * ``
274
     */
275
    @Input({ transform: booleanAttribute })
276
    public showWeekNumbers = false;
72✔
277

278
    /**
279
     * Emitted when the picker's value changes. Used for two-way binding.
280
     *
281
     * @example
282
     * ```html
283
     * <igx-date-range-picker [(value)]="date"></igx-date-range-picker>
284
     * ```
285
     */
286

287
     /**
288
      * Whether to render built-in predefined ranges.
289
      *
290
      * @example
291
      * ```html
292
      * <igx-date-range-picker [(usePredefinedRanges)]="true"></igx-date-range-picker>
293
      * ``
294
      *  */
295
    @Input() public usePredefinedRanges = false;
72✔
296

297
    /**
298
     *  Custom ranges rendered as chips.
299
     *
300
     * @example
301
     * ```html
302
     * <igx-date-range-picker [(usePredefinedRanges)]="true"></igx-date-range-picker>
303
     * ``
304
    */
305
    @Input() public customRanges: CustomDateRange[] = [];
72✔
306

307
    @Output()
308
    public valueChange = new EventEmitter<DateRange>();
72✔
309

310
    /** @hidden @internal */
311
    @HostBinding('class.igx-date-range-picker')
312
    public cssClass = 'igx-date-range-picker';
72✔
313

314
    @ViewChild(IgxInputGroupComponent, { read: ViewContainerRef })
315
    private viewContainerRef: ViewContainerRef;
316

317
    /** @hidden @internal */
318
    @ViewChild(IgxInputDirective)
319
    public inputDirective: IgxInputDirective;
320

321
    /** @hidden @internal */
322
    @ContentChildren(IgxDateRangeInputsBaseComponent)
323
    public projectedInputs: QueryList<IgxDateRangeInputsBaseComponent>;
324

325
    @ContentChild(IgxLabelDirective)
326
    public label: IgxLabelDirective;
327

328
    @ContentChild(IgxPickerActionsDirective)
329
    public pickerActions: IgxPickerActionsDirective;
330

331
    /** @hidden @internal */
332
    @ContentChild(IgxDateRangeSeparatorDirective, { read: TemplateRef })
333
    public dateSeparatorTemplate: TemplateRef<any>;
334

335
    /** @hidden @internal */
336
    public get dateSeparator(): string {
337
        if (this._dateSeparator === null) {
40✔
338
            return this.resourceStrings.igx_date_range_picker_date_separator;
40✔
339
        }
340
        return this._dateSeparator;
×
341
    }
342

343
    /** @hidden @internal */
344
    public get appliedFormat(): string {
345
        return DateTimeUtil.getLocaleDateFormat(this.locale, this.displayFormat)
506✔
346
            || DateTimeUtil.DEFAULT_INPUT_FORMAT;
347
    }
348

349
    /**
350
     * @example
351
     * ```html
352
     * <igx-date-range-picker locale="jp"></igx-date-range-picker>
353
     * ```
354
     */
355
    /**
356
     * Gets the `locale` of the date-range-picker.
357
     * If not set, defaults to application's locale.
358
     */
359
    @Input()
360
    public override get locale(): string {
361
        return this._locale;
1,034✔
362
    }
363

364
    /**
365
     * Sets the `locale` of the date-picker.
366
     * Expects a valid BCP 47 language tag.
367
     */
368
    public override set locale(value: string) {
369
        this._locale = value;
220✔
370
        // if value is invalid, set it back to _localeId
371
        try {
220✔
372
            getLocaleFirstDayOfWeek(this._locale);
220✔
373
        } catch (e) {
374
            this._locale = this._localeId;
1✔
375
        }
376
        if (this.hasProjectedInputs) {
220✔
377
            this.updateInputLocale();
3✔
378
            this.updateDisplayFormat();
3✔
379
        }
380
    }
381

382
    /** @hidden @internal */
383
    public get singleInputFormat(): string {
384
        if (this.placeholder !== '') {
236✔
385
            return this.placeholder;
2✔
386
        }
387

388
        const format = this.appliedFormat;
234✔
389
        return `${format}${SingleInputDatesConcatenationString}${format}`;
234✔
390
    }
391

392
    /**
393
     * Gets calendar state.
394
     *
395
     * ```typescript
396
     * let state = this.dateRange.collapsed;
397
     * ```
398
     */
399
    public override get collapsed(): boolean {
400
        return this._collapsed;
421✔
401
    }
402

403
    /**
404
     * The currently selected value / range from the calendar
405
     *
406
     * @remarks
407
     * The current value is of type `DateRange`
408
     *
409
     * @example
410
     * ```typescript
411
     * const newValue: DateRange = { start: new Date("2/2/2012"), end: new Date("3/3/2013")};
412
     * this.dateRangePicker.value = newValue;
413
     * ```
414
     */
415
    public get value(): DateRange | null {
416
        return this._value;
912✔
417
    }
418

419
    @Input()
420
    public set value(value: DateRange | null) {
421
        this.updateValue(value);
73✔
422
        this.onChangeCallback(value);
73✔
423
        this.valueChange.emit(value);
73✔
424
    }
425

426
    /** @hidden @internal */
427
    public get hasProjectedInputs(): boolean {
428
        return this.projectedInputs?.length > 0;
1,624✔
429
    }
430

431
    /** @hidden @internal */
432
    public get separatorClass(): string {
433
        return 'igx-date-range-picker__label';
274✔
434
    }
435

436
    protected override get toggleContainer(): HTMLElement | undefined {
437
        return this._calendarContainer;
7✔
438
    }
439

440
    private get required(): boolean {
441
        if (this._ngControl && this._ngControl.control && this._ngControl.control.validator) {
144✔
442
            const error = this._ngControl.control.validator({} as AbstractControl);
107✔
443
            return (error && error.required) ? true : false;
107!
444
        }
445

446
        return false;
37✔
447
    }
448

449
    private get calendar(): IgxCalendarComponent {
450
        return this._calendar;
629✔
451
    }
452

453
    private get dropdownOverlaySettings(): OverlaySettings {
454
        return Object.assign({}, this._dropDownOverlaySettings, this.overlaySettings);
28✔
455
    }
456

457
    private get dialogOverlaySettings(): OverlaySettings {
458
        return Object.assign({}, this._dialogOverlaySettings, this.overlaySettings);
6✔
459
    }
460

461
    private _resourceStrings = getCurrentResourceStrings(DateRangePickerResourceStringsEN);
72✔
462
    private _doneButtonText = null;
72✔
463
    private _dateSeparator = null;
72✔
464
    private _value: DateRange | null;
465
    private _overlayId: string;
466
    private _ngControl: NgControl;
467
    private _statusChanges$: Subscription;
468
    private _calendar: IgxCalendarComponent;
469
    private _calendarContainer?: HTMLElement;
470
    private _positionSettings: PositionSettings;
471
    private _focusedInput: IgxDateRangeInputsBaseComponent;
472
    private _overlaySubFilter:
72✔
473
        [MonoTypeOperatorFunction<OverlayEventArgs>, MonoTypeOperatorFunction<OverlayEventArgs | OverlayCancelableEventArgs>] = [
474
            filter(x => x.id === this._overlayId),
110✔
475
            takeUntil(merge(this._destroy$, this.closed))
476
        ];
477
    private _dialogOverlaySettings: OverlaySettings = {
72✔
478
        closeOnOutsideClick: true,
479
        modal: true,
480
        closeOnEscape: true
481
    };
482
    private _dropDownOverlaySettings: OverlaySettings = {
72✔
483
        closeOnOutsideClick: true,
484
        modal: false,
485
        closeOnEscape: true
486
    };
487
    private onChangeCallback: (dateRange: DateRange) => void = noop;
72✔
488
    private onTouchCallback: () => void = noop;
72✔
489
    private onValidatorChange: () => void = noop;
72✔
490

491
    constructor(element: ElementRef,
492
        @Inject(LOCALE_ID) _localeId: string,
493
        protected platform: PlatformUtil,
72✔
494
        private _injector: Injector,
72✔
495
        private _cdr: ChangeDetectorRef,
72✔
496
        @Inject(IgxOverlayService) private _overlayService: IgxOverlayService,
72✔
497
        @Optional() @Inject(IGX_INPUT_GROUP_TYPE) _inputGroupType?: IgxInputGroupType) {
498
        super(element, _localeId, _inputGroupType);
72✔
499
        this.locale = this.locale || this._localeId;
72!
500
    }
501

502
    /** @hidden @internal */
503
    @HostListener('keydown', ['$event'])
504
    /** @hidden @internal */
505
    public onKeyDown(event: KeyboardEvent): void {
506
        switch (event.key) {
5!
507
            case this.platform.KEYMAP.ARROW_UP:
508
                if (event.altKey) {
×
509
                    this.close();
×
510
                }
511
                break;
×
512
            case this.platform.KEYMAP.ARROW_DOWN:
513
                if (event.altKey) {
5✔
514
                    this.open();
5✔
515
                }
516
                break;
5✔
517
        }
518
    }
519

520
    /**
521
     * Opens the date range picker's dropdown or dialog.
522
     *
523
     * @example
524
     * ```html
525
     * <igx-date-range-picker #dateRange></igx-date-range-picker>
526
     *
527
     * <button type="button" igxButton (click)="dateRange.open()">Open Dialog</button
528
     * ```
529
     */
530
    public open(overlaySettings?: OverlaySettings): void {
531
        if (!this.collapsed || this.disabled) {
38✔
532
            return;
4✔
533
        }
534

535
        const settings = Object.assign({}, this.isDropdown
34✔
536
            ? this.dropdownOverlaySettings
537
            : this.dialogOverlaySettings
538
            , overlaySettings);
539

540
        this._overlayId = this._overlayService
34✔
541
            .attach(IgxCalendarContainerComponent, this.viewContainerRef, settings);
542
        this.subscribeToOverlayEvents();
34✔
543
        this._overlayService.show(this._overlayId);
34✔
544
    }
545

546
    /**
547
     * Closes the date range picker's dropdown or dialog.
548
     *
549
     * @example
550
     * ```html
551
     * <igx-date-range-picker #dateRange></igx-date-range-picker>
552
     *
553
     * <button type="button" igxButton (click)="dateRange.close()">Close Dialog</button>
554
     * ```
555
     */
556
    public close(): void {
557
        if (!this.collapsed) {
48✔
558
            this._overlayService.hide(this._overlayId);
31✔
559
        }
560
    }
561

562
    /**
563
     * Toggles the date range picker's dropdown or dialog
564
     *
565
     * @example
566
     * ```html
567
     * <igx-date-range-picker #dateRange></igx-date-range-picker>
568
     *
569
     * <button type="button" igxButton (click)="dateRange.toggle()">Toggle Dialog</button>
570
     * ```
571
     */
572
    public toggle(overlaySettings?: OverlaySettings): void {
573
        if (!this.collapsed) {
7✔
574
            this.close();
2✔
575
        } else {
576
            this.open(overlaySettings);
5✔
577
        }
578
    }
579

580
    /**
581
     * Selects a range of dates. If no `endDate` is passed, range is 1 day (only `startDate`)
582
     *
583
     * @example
584
     * ```typescript
585
     * public selectFiveDayRange() {
586
     *  const today = new Date();
587
     *  const inFiveDays = new Date(new Date().setDate(today.getDate() + 5));
588
     *  this.dateRange.select(today, inFiveDays);
589
     * }
590
     * ```
591
     */
592
    public select(startDate: Date, endDate?: Date): void {
593
        endDate = endDate ?? startDate;
19✔
594
        const dateRange = [startDate, endDate];
19✔
595
        this.handleSelection(dateRange);
19✔
596
    }
597

598
    /** @hidden @internal */
599
    public writeValue(value: DateRange): void {
600
        this.updateValue(value);
58✔
601
    }
602

603
    /** @hidden @internal */
604
    public registerOnChange(fn: any): void {
605
        this.onChangeCallback = fn;
39✔
606
    }
607

608
    /** @hidden @internal */
609
    public registerOnTouched(fn: any): void {
610
        this.onTouchCallback = fn;
38✔
611
    }
612

613
    /** @hidden @internal */
614
    public validate(control: AbstractControl): ValidationErrors | null {
615
        const value: DateRange = control.value;
199✔
616
        const errors = {};
199✔
617
        if (value) {
199✔
618
            if (this.hasProjectedInputs) {
44✔
619
                const startInput = this.projectedInputs.find(i => i instanceof IgxDateRangeStartComponent) as IgxDateRangeStartComponent;
41✔
620
                const endInput = this.projectedInputs.find(i => i instanceof IgxDateRangeEndComponent) as IgxDateRangeEndComponent;
82✔
621
                if (!startInput.dateTimeEditor.value) {
41!
622
                    Object.assign(errors, { startValue: true });
×
623
                }
624
                if (!endInput.dateTimeEditor.value) {
41✔
625
                    Object.assign(errors, { endValue: true });
1✔
626
                }
627
            }
628

629
            const min = parseDate(this.minValue);
44✔
630
            const max = parseDate(this.maxValue);
44✔
631
            const start = parseDate(value.start);
44✔
632
            const end = parseDate(value.end);
44✔
633
            if ((min && start && DateTimeUtil.lessThanMinValue(start, min, false))
44✔
634
                || (min && end && DateTimeUtil.lessThanMinValue(end, min, false))) {
635
                Object.assign(errors, { minValue: true });
2✔
636
            }
637
            if ((max && start && DateTimeUtil.greaterThanMaxValue(start, max, false))
44✔
638
                || (max && end && DateTimeUtil.greaterThanMaxValue(end, max, false))) {
639
                Object.assign(errors, { maxValue: true });
1✔
640
            }
641
        }
642

643
        return Object.keys(errors).length > 0 ? errors : null;
199✔
644
    }
645

646
    /** @hidden @internal */
647
    public registerOnValidatorChange?(fn: any): void {
648
        this.onValidatorChange = fn;
38✔
649
    }
650

651
    /** @hidden @internal */
652
    public setDisabledState?(isDisabled: boolean): void {
653
        this.disabled = isDisabled;
39✔
654
    }
655

656
    /** @hidden */
657
    public ngOnInit(): void {
658
        this._ngControl = this._injector.get<NgControl>(NgControl, null);
69✔
659

660
        this.locale = this.locale || this._localeId;
69!
661
    }
662

663
    /** @hidden */
664
    public override ngAfterViewInit(): void {
665
        super.ngAfterViewInit();
66✔
666
        this.subscribeToDateEditorEvents();
66✔
667
        this.configPositionStrategy();
66✔
668
        this.configOverlaySettings();
66✔
669
        this.cacheFocusedInput();
66✔
670
        this.attachOnTouched();
66✔
671

672
        this.setRequiredToInputs();
66✔
673

674
        if (this._ngControl) {
66✔
675
            this._statusChanges$ = this._ngControl.statusChanges.subscribe(this.onStatusChanged.bind(this));
31✔
676
        }
677

678
        // delay invocations until the current change detection cycle has completed
679
        Promise.resolve().then(() => {
66✔
680
            this.updateDisabledState();
66✔
681
            this.initialSetValue();
66✔
682
            this.updateInputs();
66✔
683
            // B.P. 07 July 2021 - IgxDateRangePicker not showing initial disabled state with ChangeDetectionStrategy.OnPush #9776
684
            /**
685
             * if disabled is placed on the range picker element and there are projected inputs
686
             * run change detection since igxInput will initially set the projected inputs' disabled to false
687
             */
688
            if (this.hasProjectedInputs && this.disabled) {
66✔
689
                this._cdr.markForCheck();
3✔
690
            }
691
        });
692
        this.updateDisplayFormat();
66✔
693
        this.updateInputFormat();
66✔
694
    }
695

696
    /** @hidden @internal */
697
    public ngOnChanges(changes: SimpleChanges): void {
698
        if (changes['displayFormat'] && this.hasProjectedInputs) {
83✔
699
            this.updateDisplayFormat();
11✔
700
        }
701
        if (changes['inputFormat'] && this.hasProjectedInputs) {
83✔
702
            this.updateInputFormat();
4✔
703
        }
704
        if (changes['disabled']) {
83✔
705
            this.updateDisabledState();
60✔
706
        }
707
    }
708

709
    /** @hidden @internal */
710
    public override ngOnDestroy(): void {
711
        super.ngOnDestroy();
56✔
712
        if (this._statusChanges$) {
56✔
713
            this._statusChanges$.unsubscribe();
31✔
714
        }
715
        if (this._overlayId) {
56✔
716
            this._overlayService.detach(this._overlayId);
8✔
717
        }
718
    }
719

720
    /** @hidden @internal */
721
    public getEditElement() {
722
        return this.inputDirective.nativeElement;
×
723
    }
724

725
    protected onStatusChanged = () => {
72✔
726
        if (this.inputGroup) {
77✔
727
            this.setValidityState(this.inputDirective, this.inputGroup.isFocused);
7✔
728
        } else if (this.hasProjectedInputs) {
70✔
729
            this.projectedInputs
70✔
730
                .forEach((i) => {
731
                    this.setValidityState(i.inputDirective, i.isFocused);
140✔
732
                });
733
        }
734
        this.setRequiredToInputs();
77✔
735
    };
736

737
    private setValidityState(inputDirective: IgxInputDirective, isFocused: boolean) {
738
        if (this._ngControl && !this._ngControl.disabled && this.isTouchedOrDirty) {
147✔
739
            if (this.hasValidators && isFocused) {
137✔
740
                inputDirective.valid = this._ngControl.valid ? IgxInputState.VALID : IgxInputState.INVALID;
2✔
741
            } else {
742
                inputDirective.valid = this._ngControl.valid ? IgxInputState.INITIAL : IgxInputState.INVALID;
135✔
743
            }
744
        } else {
745
            inputDirective.valid = IgxInputState.INITIAL;
10✔
746
        }
747
    }
748

749
    private get isTouchedOrDirty(): boolean {
750
        return (this._ngControl.control.touched || this._ngControl.control.dirty);
137✔
751
    }
752

753
    private get hasValidators(): boolean {
754
        return (!!this._ngControl.control.validator || !!this._ngControl.control.asyncValidator);
137✔
755
    }
756

757
    private handleSelection(selectionData: Date[]): void {
758
        let newValue = this.extractRange(selectionData);
37✔
759
        if (!newValue.start && !newValue.end) {
37!
760
            newValue = null;
×
761
        }
762
        this.value = newValue;
37✔
763
        if (this.isDropdown && selectionData?.length > 1) {
37✔
764
            this.close();
26✔
765
        }
766
    }
767

768
    private handleClosing(e: IBaseCancelableBrowserEventArgs): void {
769
        const args = { owner: this, cancel: e?.cancel, event: e?.event };
34✔
770
        this.closing.emit(args);
34✔
771
        e.cancel = args.cancel;
34✔
772
        if (args.cancel) {
34✔
773
            return;
2✔
774
        }
775

776
        if (this.isDropdown && e?.event && !this.isFocused) {
32!
777
            // outside click
778
            this.updateValidityOnBlur();
×
779
        } else {
780
            this.onTouchCallback();
32✔
781
            // input click
782
            if (this.hasProjectedInputs && this._focusedInput) {
32✔
783
                this._focusedInput.setFocus();
7✔
784
            }
785
            if (this.inputDirective) {
32✔
786
                this.inputDirective.focus();
15✔
787
            }
788
        }
789
    }
790

791
    private subscribeToOverlayEvents() {
792
        this._overlayService.opening.pipe(...this._overlaySubFilter).subscribe((e) => {
34✔
793
            const overlayEvent = e as OverlayCancelableEventArgs;
34✔
794
            const args = { owner: this, cancel: overlayEvent?.cancel, event: e.event };
34✔
795
            this.opening.emit(args);
34✔
796
            if (args.cancel) {
34!
797
                this._overlayService.detach(this._overlayId);
×
798
                overlayEvent.cancel = true;
×
799
                return;
×
800
            }
801

802
            this._initializeCalendarContainer(e.componentRef.instance);
34✔
803
            this._calendarContainer = e.componentRef.location.nativeElement;
34✔
804
            this._collapsed = false;
34✔
805
            this.updateCalendar();
34✔
806
        });
807

808
        this._overlayService.opened.pipe(...this._overlaySubFilter).subscribe(() => {
34✔
809
            this.calendar.wrapper.nativeElement.focus();
26✔
810
            this.opened.emit({ owner: this });
26✔
811
        });
812

813
        this._overlayService.closing.pipe(...this._overlaySubFilter).subscribe((e) => {
34✔
814
            this.handleClosing(e as OverlayCancelableEventArgs);
34✔
815
        });
816

817
        this._overlayService.closed.pipe(...this._overlaySubFilter).subscribe(() => {
34✔
818
            this._overlayService.detach(this._overlayId);
16✔
819
            this._collapsed = true;
16✔
820
            this._overlayId = null;
16✔
821
            this._calendar = null;
16✔
822
            this._calendarContainer = undefined;
16✔
823
            this.closed.emit({ owner: this });
16✔
824
        });
825
    }
826

827
    private updateValue(value: DateRange) {
828
        this._value = value ? value : null;
131✔
829
        this.updateInputs();
131✔
830
        this.updateCalendar();
131✔
831
    }
832

833
    private updateValidityOnBlur() {
834
        this._focusedInput = null;
2✔
835
        this.onTouchCallback();
2✔
836
        if (this._ngControl) {
2✔
837
            if (this.hasProjectedInputs) {
1✔
838
                this.projectedInputs.forEach(i => {
1✔
839
                    if (!this._ngControl.valid) {
2!
840
                        i.updateInputValidity(IgxInputState.INVALID);
2✔
841
                    } else {
842
                        i.updateInputValidity(IgxInputState.INITIAL);
×
843
                    }
844
                });
845
            }
846

847
            if (this.inputDirective) {
1!
848
                if (!this._ngControl.valid) {
×
849
                    this.inputDirective.valid = IgxInputState.INVALID;
×
850
                } else {
851
                    this.inputDirective.valid = IgxInputState.INITIAL;
×
852
                }
853
            }
854
        }
855
    }
856

857
    private updateDisabledState() {
858
        if (this.hasProjectedInputs) {
126✔
859
            const start = this.projectedInputs.find(i => i instanceof IgxDateRangeStartComponent) as IgxDateRangeStartComponent;
35✔
860
            const end = this.projectedInputs.find(i => i instanceof IgxDateRangeEndComponent) as IgxDateRangeEndComponent;
70✔
861
            start.inputDirective.disabled = this.disabled;
35✔
862
            end.inputDirective.disabled = this.disabled;
35✔
863
            return;
35✔
864
        }
865
    }
866

867
    private setRequiredToInputs(): void {
868
        // workaround for igxInput setting required
869
        Promise.resolve().then(() => {
143✔
870
            const isRequired = this.required;
143✔
871
            if (this.inputGroup && this.inputGroup.isRequired !== isRequired) {
143✔
872
                this.inputGroup.isRequired = isRequired;
4✔
873
            } else if (this.hasProjectedInputs && this._ngControl) {
139✔
874
                this.projectedInputs.forEach(i => i.isRequired = isRequired);
196✔
875
            }
876
        });
877
    }
878

879
    private parseMinValue(value: string | Date): Date | null {
880
        let minValue: Date = parseDate(value);
56✔
881
        if (!minValue && this.hasProjectedInputs) {
56✔
882
            const start = this.projectedInputs.filter(i => i instanceof IgxDateRangeStartComponent)[0];
52✔
883
            if (start) {
26✔
884
                minValue = parseDate(start.dateTimeEditor.minValue);
26✔
885
            }
886
        }
887

888
        return minValue;
56✔
889
    }
890

891
    private parseMaxValue(value: string | Date): Date | null {
892
        let maxValue: Date = parseDate(value);
56✔
893
        if (!maxValue && this.projectedInputs) {
56✔
894
            const end = this.projectedInputs.filter(i => i instanceof IgxDateRangeEndComponent)[0];
54✔
895
            if (end) {
54✔
896
                maxValue = parseDate(end.dateTimeEditor.maxValue);
26✔
897
            }
898
        }
899

900
        return maxValue;
56✔
901
    }
902

903
    private updateCalendar(): void {
904
        if (!this.calendar) {
167✔
905
            return;
111✔
906
        }
907
        this.calendar.disabledDates = [];
56✔
908
        const minValue = this.parseMinValue(this.minValue);
56✔
909
        if (minValue) {
56✔
910
            this.calendar.disabledDates.push({ type: DateRangeType.Before, dateRange: [minValue] });
2✔
911
        }
912
        const maxValue = this.parseMaxValue(this.maxValue);
56✔
913
        if (maxValue) {
56✔
914
            this.calendar.disabledDates.push({ type: DateRangeType.After, dateRange: [maxValue] });
2✔
915
        }
916

917
        const range: Date[] = [];
56✔
918
        if (this.value?.start && this.value?.end) {
56✔
919
            const _value = this.toRangeOfDates(this.value);
21✔
920
            if (DateTimeUtil.greaterThanMaxValue(_value.start, _value.end)) {
21!
921
                this.swapEditorDates();
×
922
            }
923
            if (this.valueInRange(this.value, minValue, maxValue)) {
21✔
924
                range.push(_value.start, _value.end);
21✔
925
            }
926
        }
927

928
        if (range.length > 0) {
56✔
929
            this.calendar.selectDate(range);
21✔
930
        } else if (range.length === 0 && this.calendar.monthViews) {
35!
931
            this.calendar.deselectDate();
×
932
        }
933
        this.calendar.viewDate = range[0] || new Date();
56✔
934
    }
935

936
    private swapEditorDates(): void {
937
        if (this.hasProjectedInputs) {
×
938
            const start = this.projectedInputs.find(i => i instanceof IgxDateRangeStartComponent) as IgxDateRangeStartComponent;
×
939
            const end = this.projectedInputs.find(i => i instanceof IgxDateRangeEndComponent) as IgxDateRangeEndComponent;
×
940
            [start.dateTimeEditor.value, end.dateTimeEditor.value] = [end.dateTimeEditor.value, start.dateTimeEditor.value];
×
941
            [this.value.start, this.value.end] = [this.value.end, this.value.start];
×
942
        }
943
    }
944

945
    private valueInRange(value: DateRange, minValue?: Date, maxValue?: Date): boolean {
946
        const _value = this.toRangeOfDates(value);
21✔
947
        if (minValue && DateTimeUtil.lessThanMinValue(_value.start, minValue, false)) {
21!
948
            return false;
×
949
        }
950
        if (maxValue && DateTimeUtil.greaterThanMaxValue(_value.end, maxValue, false)) {
21!
951
            return false;
×
952
        }
953

954
        return true;
21✔
955
    }
956

957
    private extractRange(selection: Date[]): DateRange {
958
        return {
37✔
959
            start: selection[0] || null,
37!
960
            end: selection.length > 0 ? selection[selection.length - 1] : null
37!
961
        };
962
    }
963

964
    private toRangeOfDates(range: DateRange): { start: Date; end: Date } {
965
        let start;
966
        let end;
967
        if (!isDate(range.start)) {
85✔
968
            start = DateTimeUtil.parseIsoDate(range.start);
1✔
969
        }
970
        if (!isDate(range.end)) {
85✔
971
            end = DateTimeUtil.parseIsoDate(range.end);
2✔
972
        }
973

974
        if (start || end) {
85!
975
            return { start, end };
×
976
        }
977

978
        return { start: range.start as Date, end: range.end as Date };
85✔
979
    }
980

981
    private subscribeToDateEditorEvents(): void {
982
        if (this.hasProjectedInputs) {
66✔
983
            const start = this.projectedInputs.find(i => i instanceof IgxDateRangeStartComponent) as IgxDateRangeStartComponent;
30✔
984
            const end = this.projectedInputs.find(i => i instanceof IgxDateRangeEndComponent) as IgxDateRangeEndComponent;
60✔
985
            if (start && end) {
30✔
986
                start.dateTimeEditor.valueChange
30✔
987
                    .pipe(takeUntil(this._destroy$))
988
                    .subscribe(value => {
989
                        if (this.value) {
1!
990
                            this.value = { start: value, end: this.value.end };
×
991
                        } else {
992
                            this.value = { start: value, end: null };
1✔
993
                        }
994
                    });
995
                end.dateTimeEditor.valueChange
30✔
996
                    .pipe(takeUntil(this._destroy$))
997
                    .subscribe(value => {
998
                        if (this.value) {
1!
999
                            this.value = { start: this.value.start, end: value as Date };
1✔
1000
                        } else {
1001
                            this.value = { start: null, end: value as Date };
×
1002
                        }
1003
                    });
1004
            }
1005
        }
1006
    }
1007

1008
    private attachOnTouched(): void {
1009
        if (this.hasProjectedInputs) {
66✔
1010
            this.projectedInputs.forEach(i => {
30✔
1011
                fromEvent(i.dateTimeEditor.nativeElement, 'blur')
60✔
1012
                    .pipe(takeUntil(this._destroy$))
1013
                    .subscribe(() => {
1014
                        if (this.collapsed) {
9✔
1015
                            this.updateValidityOnBlur();
1✔
1016
                        }
1017
                    });
1018
            });
1019
        } else {
1020
            fromEvent(this.inputDirective.nativeElement, 'blur')
36✔
1021
                .pipe(takeUntil(this._destroy$))
1022
                .subscribe(() => {
1023
                    if (this.collapsed) {
7!
1024
                        this.updateValidityOnBlur();
×
1025
                    }
1026
                });
1027
        }
1028
    }
1029

1030
    private cacheFocusedInput(): void {
1031
        if (this.hasProjectedInputs) {
66✔
1032
            this.projectedInputs.forEach(i => {
30✔
1033
                fromEvent(i.dateTimeEditor.nativeElement, 'focus')
60✔
1034
                    .pipe(takeUntil(this._destroy$))
1035
                    .subscribe(() => this._focusedInput = i);
13✔
1036
            });
1037
        }
1038
    }
1039

1040
    private configPositionStrategy(): void {
1041
        this._positionSettings = {
66✔
1042
            openAnimation: fadeIn,
1043
            closeAnimation: fadeOut
1044
        };
1045
        this._dropDownOverlaySettings.positionStrategy = new AutoPositionStrategy(this._positionSettings);
66✔
1046
        this._dropDownOverlaySettings.target = this.element.nativeElement;
66✔
1047
    }
1048

1049
    private configOverlaySettings(): void {
1050
        if (this.overlaySettings !== null) {
66✔
1051
            this._dropDownOverlaySettings = Object.assign({}, this._dropDownOverlaySettings, this.overlaySettings);
66✔
1052
            this._dialogOverlaySettings = Object.assign({}, this._dialogOverlaySettings, this.overlaySettings);
66✔
1053
        }
1054
    }
1055

1056
    private initialSetValue() {
1057
        // if there is no value and no ngControl on the picker but we have inputs we may have value set through
1058
        // their ngModels - we should generate our initial control value
1059
        if ((!this.value || (!this.value.start && !this.value.end)) && this.hasProjectedInputs && !this._ngControl) {
66!
1060
            const start = this.projectedInputs.find(i => i instanceof IgxDateRangeStartComponent);
2✔
1061
            const end = this.projectedInputs.find(i => i instanceof IgxDateRangeEndComponent);
4✔
1062
            this._value = {
2✔
1063
                start: start.dateTimeEditor.value as Date,
1064
                end: end.dateTimeEditor.value as Date
1065
            };
1066
        }
1067
    }
1068

1069
    private updateInputs(): void {
1070
        const start = this.projectedInputs?.find(i => i instanceof IgxDateRangeStartComponent) as IgxDateRangeStartComponent;
197✔
1071
        const end = this.projectedInputs?.find(i => i instanceof IgxDateRangeEndComponent) as IgxDateRangeEndComponent;
197✔
1072
        if (start && end) {
197✔
1073
            const _value = this.value ? this.toRangeOfDates(this.value) : null;
96✔
1074
            start.updateInputValue(_value?.start || null);
96✔
1075
            end.updateInputValue(_value?.end || null);
96✔
1076
        }
1077
    }
1078

1079
    private updateDisplayFormat(): void {
1080
        this.projectedInputs.forEach(i => {
80✔
1081
            const input = i as IgxDateRangeInputsBaseComponent;
88✔
1082
            input.dateTimeEditor.displayFormat = this.displayFormat;
88✔
1083
        });
1084
    }
1085

1086
    private updateInputFormat(): void {
1087
        this.projectedInputs.forEach(i => {
70✔
1088
            const input = i as IgxDateRangeInputsBaseComponent;
68✔
1089
            if (input.dateTimeEditor.inputFormat !== this.inputFormat) {
68✔
1090
                input.dateTimeEditor.inputFormat = this.inputFormat;
68✔
1091
            }
1092
        });
1093
    }
1094

1095
    private updateInputLocale(): void {
1096
        this.projectedInputs.forEach(i => {
3✔
1097
            const input = i as IgxDateRangeInputsBaseComponent;
6✔
1098
            input.dateTimeEditor.locale = this.locale;
6✔
1099
        });
1100
    }
1101

1102
    private _initializeCalendarContainer(componentInstance: IgxCalendarContainerComponent) {
1103
        this._calendar = componentInstance.calendar;
34✔
1104
        this.calendar.hasHeader = false;
34✔
1105
        this.calendar.locale = this.locale;
34✔
1106
        this.calendar.selection = CalendarSelection.RANGE;
34✔
1107
        this.calendar.weekStart = this.weekStart;
34✔
1108
        this.calendar.hideOutsideDays = this.hideOutsideDays;
34✔
1109
        this.calendar.monthsViewNumber = this.displayMonthsCount;
34✔
1110
        this.calendar.showWeekNumbers = this.showWeekNumbers;
34✔
1111
        this.calendar.selected.pipe(takeUntil(this._destroy$)).subscribe((ev: Date[]) => this.handleSelection(ev));
34✔
1112

1113
        componentInstance.mode = this.mode;
34✔
1114
        componentInstance.closeButtonLabel = !this.isDropdown ? this.doneButtonText : null;
34✔
1115
        componentInstance.pickerActions = this.pickerActions;
34✔
1116
        componentInstance.usePredefinedRanges = this.usePredefinedRanges;
34✔
1117
        componentInstance.customRanges = this.customRanges;
34✔
1118
        componentInstance.resourceStrings = this.resourceStrings;
34✔
1119
        componentInstance.calendarClose.pipe(takeUntil(this._destroy$)).subscribe(() => this.close());
34✔
1120
        componentInstance.rangeSelected
34✔
1121
        .pipe(takeUntil(this._destroy$))
1122
        .subscribe((r: DateRange) => {
NEW
1123
            if (r?.start && r?.end) {
×
NEW
1124
            this.select(new Date(r.start), new Date(r.end));
×
1125
            }
1126

NEW
1127
            if (this.isDropdown) {
×
NEW
1128
            this.close();
×
1129
            }
1130
        });
1131
    }
1132
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc