-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
Copy pathselect.ts
1446 lines (1248 loc) · 46.4 KB
/
select.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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
_IdGenerator,
ActiveDescendantKeyManager,
addAriaReferencedId,
LiveAnnouncer,
removeAriaReferencedId,
} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {SelectionModel} from '@angular/cdk/collections';
import {
A,
DOWN_ARROW,
ENTER,
hasModifierKey,
LEFT_ARROW,
RIGHT_ARROW,
SPACE,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {
CdkConnectedOverlay,
CdkOverlayOrigin,
ConnectedPosition,
Overlay,
ScrollStrategy,
} from '@angular/cdk/overlay';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
AfterContentInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
Directive,
DoCheck,
ElementRef,
EventEmitter,
inject,
InjectionToken,
Input,
numberAttribute,
OnChanges,
OnDestroy,
OnInit,
Output,
QueryList,
SimpleChanges,
ViewChild,
ViewEncapsulation,
HostAttributeToken,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
FormGroupDirective,
NgControl,
NgForm,
Validators,
} from '@angular/forms';
import {
_countGroupLabelsBeforeOption,
_ErrorStateTracker,
_getOptionScrollPosition,
ErrorStateMatcher,
MAT_OPTGROUP,
MAT_OPTION_PARENT_COMPONENT,
MatOptgroup,
MatOption,
MatOptionSelectionChange,
} from '@angular/material/core';
import {MAT_FORM_FIELD, MatFormField, MatFormFieldControl} from '@angular/material/form-field';
import {defer, merge, Observable, Subject} from 'rxjs';
import {
distinctUntilChanged,
filter,
map,
startWith,
switchMap,
take,
takeUntil,
} from 'rxjs/operators';
import {matSelectAnimations} from './select-animations';
import {
getMatSelectDynamicMultipleError,
getMatSelectNonArrayValueError,
getMatSelectNonFunctionValueError,
} from './select-errors';
import {NgClass} from '@angular/common';
/** Injection token that determines the scroll handling while a select is open. */
export const MAT_SELECT_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>(
'mat-select-scroll-strategy',
{
providedIn: 'root',
factory: () => {
const overlay = inject(Overlay);
return () => overlay.scrollStrategies.reposition();
},
},
);
/** @docs-private */
export function MAT_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY(
overlay: Overlay,
): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** Object that can be used to configure the default options for the select module. */
export interface MatSelectConfig {
/** Whether option centering should be disabled. */
disableOptionCentering?: boolean;
/** Time to wait in milliseconds after the last keystroke before moving focus to an item. */
typeaheadDebounceInterval?: number;
/** Class or list of classes to be applied to the menu's overlay panel. */
overlayPanelClass?: string | string[];
/** Whether icon indicators should be hidden for single-selection. */
hideSingleSelectionIndicator?: boolean;
/**
* Width of the panel. If set to `auto`, the panel will match the trigger width.
* If set to null or an empty string, the panel will grow to match the longest option's text.
*/
panelWidth?: string | number | null;
/**
* Whether nullable options can be selected by default.
* See `MatSelect.canSelectNullableOptions` for more information.
*/
canSelectNullableOptions?: boolean;
}
/** Injection token that can be used to provide the default options the select module. */
export const MAT_SELECT_CONFIG = new InjectionToken<MatSelectConfig>('MAT_SELECT_CONFIG');
/** @docs-private */
export const MAT_SELECT_SCROLL_STRATEGY_PROVIDER = {
provide: MAT_SELECT_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY,
};
/**
* Injection token that can be used to reference instances of `MatSelectTrigger`. It serves as
* alternative token to the actual `MatSelectTrigger` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_SELECT_TRIGGER = new InjectionToken<MatSelectTrigger>('MatSelectTrigger');
/** Change event object that is emitted when the select value has changed. */
export class MatSelectChange {
constructor(
/** Reference to the select that emitted the change event. */
public source: MatSelect,
/** Current value of the select that emitted the event. */
public value: any,
) {}
}
@Component({
selector: 'mat-select',
exportAs: 'matSelect',
templateUrl: 'select.html',
styleUrl: 'select.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'role': 'combobox',
'aria-haspopup': 'listbox',
'class': 'mat-mdc-select',
'[attr.id]': 'id',
'[attr.tabindex]': 'disabled ? -1 : tabIndex',
'[attr.aria-controls]': 'panelOpen ? id + "-panel" : null',
'[attr.aria-expanded]': 'panelOpen',
'[attr.aria-label]': 'ariaLabel || null',
'[attr.aria-required]': 'required.toString()',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-invalid]': 'errorState',
'[attr.aria-activedescendant]': '_getAriaActiveDescendant()',
'[class.mat-mdc-select-disabled]': 'disabled',
'[class.mat-mdc-select-invalid]': 'errorState',
'[class.mat-mdc-select-required]': 'required',
'[class.mat-mdc-select-empty]': 'empty',
'[class.mat-mdc-select-multiple]': 'multiple',
'(keydown)': '_handleKeydown($event)',
'(focus)': '_onFocus()',
'(blur)': '_onBlur()',
},
animations: [matSelectAnimations.transformPanel],
providers: [
{provide: MatFormFieldControl, useExisting: MatSelect},
{provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatSelect},
],
imports: [CdkOverlayOrigin, CdkConnectedOverlay, NgClass],
})
export class MatSelect
implements
AfterContentInit,
OnChanges,
OnDestroy,
OnInit,
DoCheck,
ControlValueAccessor,
MatFormFieldControl<any>
{
protected _viewportRuler = inject(ViewportRuler);
protected _changeDetectorRef = inject(ChangeDetectorRef);
readonly _elementRef = inject(ElementRef);
private _dir = inject(Directionality, {optional: true});
private _idGenerator = inject(_IdGenerator);
protected _parentFormField = inject<MatFormField>(MAT_FORM_FIELD, {optional: true});
ngControl = inject(NgControl, {self: true, optional: true})!;
private _liveAnnouncer = inject(LiveAnnouncer);
protected _defaultOptions = inject(MAT_SELECT_CONFIG, {optional: true});
private _initialized = new Subject();
/** All of the defined select options. */
@ContentChildren(MatOption, {descendants: true}) options: QueryList<MatOption>;
// TODO(crisbeto): this is only necessary for the non-MDC select, but it's technically a
// public API so we have to keep it. It should be deprecated and removed eventually.
/** All of the defined groups of options. */
@ContentChildren(MAT_OPTGROUP, {descendants: true}) optionGroups: QueryList<MatOptgroup>;
/** User-supplied override of the trigger element. */
@ContentChild(MAT_SELECT_TRIGGER) customTrigger: MatSelectTrigger;
/**
* This position config ensures that the top "start" corner of the overlay
* is aligned with with the top "start" of the origin by default (overlapping
* the trigger completely). If the panel cannot fit below the trigger, it
* will fall back to a position above the trigger.
*/
_positions: ConnectedPosition[] = [
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top',
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top',
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom',
panelClass: 'mat-mdc-select-panel-above',
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom',
panelClass: 'mat-mdc-select-panel-above',
},
];
/** Scrolls a particular option into the view. */
_scrollOptionIntoView(index: number): void {
const option = this.options.toArray()[index];
if (option) {
const panel: HTMLElement = this.panel.nativeElement;
const labelCount = _countGroupLabelsBeforeOption(index, this.options, this.optionGroups);
const element = option._getHostElement();
if (index === 0 && labelCount === 1) {
// If we've got one group label before the option and we're at the top option,
// scroll the list to the top. This is better UX than scrolling the list to the
// top of the option, because it allows the user to read the top group's label.
panel.scrollTop = 0;
} else {
panel.scrollTop = _getOptionScrollPosition(
element.offsetTop,
element.offsetHeight,
panel.scrollTop,
panel.offsetHeight,
);
}
}
}
/** Called when the panel has been opened and the overlay has settled on its final position. */
private _positioningSettled() {
this._scrollOptionIntoView(this._keyManager.activeItemIndex || 0);
}
/** Creates a change event object that should be emitted by the select. */
private _getChangeEvent(value: any) {
return new MatSelectChange(this, value);
}
/** Factory function used to create a scroll strategy for this select. */
private _scrollStrategyFactory = inject(MAT_SELECT_SCROLL_STRATEGY);
/** Whether or not the overlay panel is open. */
private _panelOpen = false;
/** Comparison function to specify which option is displayed. Defaults to object equality. */
private _compareWith = (o1: any, o2: any) => o1 === o2;
/** Unique id for this input. */
private _uid = this._idGenerator.getId('mat-select-');
/** Current `aria-labelledby` value for the select trigger. */
private _triggerAriaLabelledBy: string | null = null;
/**
* Keeps track of the previous form control assigned to the select.
* Used to detect if it has changed.
*/
private _previousControl: AbstractControl | null | undefined;
/** Emits whenever the component is destroyed. */
protected readonly _destroy = new Subject<void>();
/** Tracks the error state of the select. */
private _errorStateTracker: _ErrorStateTracker;
/**
* Emits whenever the component state changes and should cause the parent
* form-field to update. Implemented as part of `MatFormFieldControl`.
* @docs-private
*/
readonly stateChanges = new Subject<void>();
/**
* Disable the automatic labeling to avoid issues like #27241.
* @docs-private
*/
readonly disableAutomaticLabeling = true;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input('aria-describedby') userAriaDescribedBy: string;
/** Deals with the selection logic. */
_selectionModel: SelectionModel<MatOption>;
/** Manages keyboard events for options in the panel. */
_keyManager: ActiveDescendantKeyManager<MatOption>;
/** Ideal origin for the overlay panel. */
_preferredOverlayOrigin: CdkOverlayOrigin | ElementRef | undefined;
/** Width of the overlay panel. */
_overlayWidth: string | number;
/** `View -> model callback called when value changes` */
_onChange: (value: any) => void = () => {};
/** `View -> model callback called when select has been touched` */
_onTouched = () => {};
/** ID for the DOM node containing the select's value. */
_valueId = this._idGenerator.getId('mat-select-value-');
/** Emits when the panel element is finished transforming in. */
readonly _panelDoneAnimatingStream = new Subject<string>();
/** Strategy that will be used to handle scrolling while the select panel is open. */
_scrollStrategy: ScrollStrategy;
_overlayPanelClass: string | string[] = this._defaultOptions?.overlayPanelClass || '';
/** Whether the select is focused. */
get focused(): boolean {
return this._focused || this._panelOpen;
}
private _focused = false;
/** A name for this control that can be used by `mat-form-field`. */
controlType = 'mat-select';
/** Trigger that opens the select. */
@ViewChild('trigger') trigger: ElementRef;
/** Panel containing the select options. */
@ViewChild('panel') panel: ElementRef;
/** Overlay pane containing the options. */
@ViewChild(CdkConnectedOverlay)
protected _overlayDir: CdkConnectedOverlay;
/** Classes to be passed to the select panel. Supports the same syntax as `ngClass`. */
@Input() panelClass: string | string[] | Set<string> | {[key: string]: any};
/** Whether the select is disabled. */
@Input({transform: booleanAttribute})
disabled: boolean = false;
/** Whether ripples in the select are disabled. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
/** Tab index of the select. */
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
})
tabIndex: number = 0;
/** Whether checkmark indicator for single-selection options is hidden. */
@Input({transform: booleanAttribute})
get hideSingleSelectionIndicator(): boolean {
return this._hideSingleSelectionIndicator;
}
set hideSingleSelectionIndicator(value: boolean) {
this._hideSingleSelectionIndicator = value;
this._syncParentProperties();
}
private _hideSingleSelectionIndicator: boolean =
this._defaultOptions?.hideSingleSelectionIndicator ?? false;
/** Placeholder to be shown if no value has been selected. */
@Input()
get placeholder(): string {
return this._placeholder;
}
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
private _placeholder: string;
/** Whether the component is required. */
@Input({transform: booleanAttribute})
get required(): boolean {
return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false;
}
set required(value: boolean) {
this._required = value;
this.stateChanges.next();
}
private _required: boolean | undefined;
/** Whether the user should be allowed to select multiple options. */
@Input({transform: booleanAttribute})
get multiple(): boolean {
return this._multiple;
}
set multiple(value: boolean) {
if (this._selectionModel && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectDynamicMultipleError();
}
this._multiple = value;
}
private _multiple: boolean = false;
/** Whether to center the active option over the trigger. */
@Input({transform: booleanAttribute})
disableOptionCentering = this._defaultOptions?.disableOptionCentering ?? false;
/**
* Function to compare the option values with the selected values. The first argument
* is a value from an option. The second is a value from the selection. A boolean
* should be returned.
*/
@Input()
get compareWith() {
return this._compareWith;
}
set compareWith(fn: (o1: any, o2: any) => boolean) {
if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectNonFunctionValueError();
}
this._compareWith = fn;
if (this._selectionModel) {
// A different comparator means the selection could change.
this._initializeSelection();
}
}
/** Value of the select control. */
@Input()
get value(): any {
return this._value;
}
set value(newValue: any) {
const hasAssigned = this._assignValue(newValue);
if (hasAssigned) {
this._onChange(newValue);
}
}
private _value: any;
/** Aria label of the select. */
@Input('aria-label') ariaLabel: string = '';
/** Input that can be used to specify the `aria-labelledby` attribute. */
@Input('aria-labelledby') ariaLabelledby: string;
/** Object used to control when error messages are shown. */
@Input()
get errorStateMatcher() {
return this._errorStateTracker.matcher;
}
set errorStateMatcher(value: ErrorStateMatcher) {
this._errorStateTracker.matcher = value;
}
/** Time to wait in milliseconds after the last keystroke before moving focus to an item. */
@Input({transform: numberAttribute})
typeaheadDebounceInterval: number;
/**
* Function used to sort the values in a select in multiple mode.
* Follows the same logic as `Array.prototype.sort`.
*/
@Input() sortComparator: (a: MatOption, b: MatOption, options: MatOption[]) => number;
/** Unique id of the element. */
@Input()
get id(): string {
return this._id;
}
set id(value: string) {
this._id = value || this._uid;
this.stateChanges.next();
}
private _id: string;
/** Whether the select is in an error state. */
get errorState() {
return this._errorStateTracker.errorState;
}
set errorState(value: boolean) {
this._errorStateTracker.errorState = value;
}
/**
* Width of the panel. If set to `auto`, the panel will match the trigger width.
* If set to null or an empty string, the panel will grow to match the longest option's text.
*/
@Input() panelWidth: string | number | null =
this._defaultOptions && typeof this._defaultOptions.panelWidth !== 'undefined'
? this._defaultOptions.panelWidth
: 'auto';
/**
* By default selecting an option with a `null` or `undefined` value will reset the select's
* value. Enable this option if the reset behavior doesn't match your requirements and instead
* the nullable options should become selected. The value of this input can be controlled app-wide
* using the `MAT_SELECT_CONFIG` injection token.
*/
@Input({transform: booleanAttribute})
canSelectNullableOptions: boolean = this._defaultOptions?.canSelectNullableOptions ?? false;
/** Combined stream of all of the child options' change events. */
readonly optionSelectionChanges: Observable<MatOptionSelectionChange> = defer(() => {
const options = this.options;
if (options) {
return options.changes.pipe(
startWith(options),
switchMap(() => merge(...options.map(option => option.onSelectionChange))),
);
}
return this._initialized.pipe(switchMap(() => this.optionSelectionChanges));
});
/** Event emitted when the select panel has been toggled. */
@Output() readonly openedChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/** Event emitted when the select has been opened. */
@Output('opened') readonly _openedStream: Observable<void> = this.openedChange.pipe(
filter(o => o),
map(() => {}),
);
/** Event emitted when the select has been closed. */
@Output('closed') readonly _closedStream: Observable<void> = this.openedChange.pipe(
filter(o => !o),
map(() => {}),
);
/** Event emitted when the selected value has been changed by the user. */
@Output() readonly selectionChange = new EventEmitter<MatSelectChange>();
/**
* Event that emits whenever the raw value of the select changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
* @docs-private
*/
@Output() readonly valueChange: EventEmitter<any> = new EventEmitter<any>();
constructor(...args: unknown[]);
constructor() {
const defaultErrorStateMatcher = inject(ErrorStateMatcher);
const parentForm = inject(NgForm, {optional: true});
const parentFormGroup = inject(FormGroupDirective, {optional: true});
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
if (this.ngControl) {
// Note: we provide the value accessor through here, instead of
// the `providers` to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
// Note that we only want to set this when the defaults pass it in, otherwise it should
// stay as `undefined` so that it falls back to the default in the key manager.
if (this._defaultOptions?.typeaheadDebounceInterval != null) {
this.typeaheadDebounceInterval = this._defaultOptions.typeaheadDebounceInterval;
}
this._errorStateTracker = new _ErrorStateTracker(
defaultErrorStateMatcher,
this.ngControl,
parentFormGroup,
parentForm,
this.stateChanges,
);
this._scrollStrategy = this._scrollStrategyFactory();
this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0;
// Force setter to be called in case id was not specified.
this.id = this.id;
}
ngOnInit() {
this._selectionModel = new SelectionModel<MatOption>(this.multiple);
this.stateChanges.next();
// We need `distinctUntilChanged` here, because some browsers will
// fire the animation end event twice for the same animation. See:
// https://github.com/angular/angular/issues/24084
this._panelDoneAnimatingStream
.pipe(distinctUntilChanged(), takeUntil(this._destroy))
.subscribe(() => this._panelDoneAnimating(this.panelOpen));
this._viewportRuler
.change()
.pipe(takeUntil(this._destroy))
.subscribe(() => {
if (this.panelOpen) {
this._overlayWidth = this._getOverlayWidth(this._preferredOverlayOrigin);
this._changeDetectorRef.detectChanges();
}
});
}
ngAfterContentInit() {
this._initialized.next();
this._initialized.complete();
this._initKeyManager();
this._selectionModel.changed.pipe(takeUntil(this._destroy)).subscribe(event => {
event.added.forEach(option => option.select());
event.removed.forEach(option => option.deselect());
});
this.options.changes.pipe(startWith(null), takeUntil(this._destroy)).subscribe(() => {
this._resetOptions();
this._initializeSelection();
});
}
ngDoCheck() {
const newAriaLabelledby = this._getTriggerAriaLabelledby();
const ngControl = this.ngControl;
// We have to manage setting the `aria-labelledby` ourselves, because part of its value
// is computed as a result of a content query which can cause this binding to trigger a
// "changed after checked" error.
if (newAriaLabelledby !== this._triggerAriaLabelledBy) {
const element: HTMLElement = this._elementRef.nativeElement;
this._triggerAriaLabelledBy = newAriaLabelledby;
if (newAriaLabelledby) {
element.setAttribute('aria-labelledby', newAriaLabelledby);
} else {
element.removeAttribute('aria-labelledby');
}
}
if (ngControl) {
// The disabled state might go out of sync if the form group is swapped out. See #17860.
if (this._previousControl !== ngControl.control) {
if (
this._previousControl !== undefined &&
ngControl.disabled !== null &&
ngControl.disabled !== this.disabled
) {
this.disabled = ngControl.disabled;
}
this._previousControl = ngControl.control;
}
this.updateErrorState();
}
}
ngOnChanges(changes: SimpleChanges) {
// Updating the disabled state is handled by the input, but we need to additionally let
// the parent form field know to run change detection when the disabled state changes.
if (changes['disabled'] || changes['userAriaDescribedBy']) {
this.stateChanges.next();
}
if (changes['typeaheadDebounceInterval'] && this._keyManager) {
this._keyManager.withTypeAhead(this.typeaheadDebounceInterval);
}
}
ngOnDestroy() {
this._keyManager?.destroy();
this._destroy.next();
this._destroy.complete();
this.stateChanges.complete();
this._clearFromModal();
}
/** Toggles the overlay panel open or closed. */
toggle(): void {
this.panelOpen ? this.close() : this.open();
}
/** Opens the overlay panel. */
open(): void {
if (!this._canOpen()) {
return;
}
// It's important that we read this as late as possible, because doing so earlier will
// return a different element since it's based on queries in the form field which may
// not have run yet. Also this needs to be assigned before we measure the overlay width.
if (this._parentFormField) {
this._preferredOverlayOrigin = this._parentFormField.getConnectedOverlayOrigin();
}
this._overlayWidth = this._getOverlayWidth(this._preferredOverlayOrigin);
this._applyModalPanelOwnership();
this._panelOpen = true;
this._keyManager.withHorizontalOrientation(null);
this._highlightCorrectOption();
this._changeDetectorRef.markForCheck();
// Required for the MDC form field to pick up when the overlay has been opened.
this.stateChanges.next();
}
/**
* Track which modal we have modified the `aria-owns` attribute of. When the combobox trigger is
* inside an aria-modal, we apply aria-owns to the parent modal with the `id` of the options
* panel. Track the modal we have changed so we can undo the changes on destroy.
*/
private _trackedModal: Element | null = null;
/**
* If the autocomplete trigger is inside of an `aria-modal` element, connect
* that modal to the options panel with `aria-owns`.
*
* For some browser + screen reader combinations, when navigation is inside
* of an `aria-modal` element, the screen reader treats everything outside
* of that modal as hidden or invisible.
*
* This causes a problem when the combobox trigger is _inside_ of a modal, because the
* options panel is rendered _outside_ of that modal, preventing screen reader navigation
* from reaching the panel.
*
* We can work around this issue by applying `aria-owns` to the modal with the `id` of
* the options panel. This effectively communicates to assistive technology that the
* options panel is part of the same interaction as the modal.
*
* At time of this writing, this issue is present in VoiceOver.
* See https://github.com/angular/components/issues/20694
*/
private _applyModalPanelOwnership() {
// TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with
// the `LiveAnnouncer` and any other usages.
//
// Note that the selector here is limited to CDK overlays at the moment in order to reduce the
// section of the DOM we need to look through. This should cover all the cases we support, but
// the selector can be expanded if it turns out to be too narrow.
const modal = this._elementRef.nativeElement.closest(
'body > .cdk-overlay-container [aria-modal="true"]',
);
if (!modal) {
// Most commonly, the autocomplete trigger is not inside a modal.
return;
}
const panelId = `${this.id}-panel`;
if (this._trackedModal) {
removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId);
}
addAriaReferencedId(modal, 'aria-owns', panelId);
this._trackedModal = modal;
}
/** Clears the reference to the listbox overlay element from the modal it was added to. */
private _clearFromModal() {
if (!this._trackedModal) {
// Most commonly, the autocomplete trigger is not used inside a modal.
return;
}
const panelId = `${this.id}-panel`;
removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId);
this._trackedModal = null;
}
/** Closes the overlay panel and focuses the host element. */
close(): void {
if (this._panelOpen) {
this._panelOpen = false;
this._keyManager.withHorizontalOrientation(this._isRtl() ? 'rtl' : 'ltr');
this._changeDetectorRef.markForCheck();
this._onTouched();
// Required for the MDC form field to pick up when the overlay has been closed.
this.stateChanges.next();
}
}
/**
* Sets the select's value. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param value New value to be written to the model.
*/
writeValue(value: any): void {
this._assignValue(value);
}
/**
* Saves a callback function to be invoked when the select's value
* changes from user input. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the value changes.
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Saves a callback function to be invoked when the select is blurred
* by the user. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the component has been touched.
*/
registerOnTouched(fn: () => {}): void {
this._onTouched = fn;
}
/**
* Disables the select. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
}
/** Whether or not the overlay panel is open. */
get panelOpen(): boolean {
return this._panelOpen;
}
/** The currently selected option. */
get selected(): MatOption | MatOption[] {
return this.multiple ? this._selectionModel?.selected || [] : this._selectionModel?.selected[0];
}
/** The value displayed in the trigger. */
get triggerValue(): string {
if (this.empty) {
return '';
}
if (this._multiple) {
const selectedOptions = this._selectionModel.selected.map(option => option.viewValue);
if (this._isRtl()) {
selectedOptions.reverse();
}
// TODO(crisbeto): delimiter should be configurable for proper localization.
return selectedOptions.join(', ');
}
return this._selectionModel.selected[0].viewValue;
}
/** Refreshes the error state of the select. */
updateErrorState() {
this._errorStateTracker.updateErrorState();
}
/** Whether the element is in RTL mode. */
_isRtl(): boolean {
return this._dir ? this._dir.value === 'rtl' : false;
}
/** Handles all keydown events on the select. */
_handleKeydown(event: KeyboardEvent): void {
if (!this.disabled) {
this.panelOpen ? this._handleOpenKeydown(event) : this._handleClosedKeydown(event);
}
}
/** Handles keyboard events while the select is closed. */
private _handleClosedKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
const isArrowKey =
keyCode === DOWN_ARROW ||
keyCode === UP_ARROW ||
keyCode === LEFT_ARROW ||
keyCode === RIGHT_ARROW;
const isOpenKey = keyCode === ENTER || keyCode === SPACE;
const manager = this._keyManager;
// Open the select on ALT + arrow key to match the native <select>
if (
(!manager.isTyping() && isOpenKey && !hasModifierKey(event)) ||
((this.multiple || event.altKey) && isArrowKey)
) {
event.preventDefault(); // prevents the page from scrolling down when pressing space
this.open();
} else if (!this.multiple) {
const previouslySelectedOption = this.selected;
manager.onKeydown(event);
const selectedOption = this.selected;
// Since the value has changed, we need to announce it ourselves.
if (selectedOption && previouslySelectedOption !== selectedOption) {
// We set a duration on the live announcement, because we want the live element to be
// cleared after a while so that users can't navigate to it using the arrow keys.
this._liveAnnouncer.announce((selectedOption as MatOption).viewValue, 10000);
}
}
}
/** Handles keyboard events when the selected is open. */
private _handleOpenKeydown(event: KeyboardEvent): void {
const manager = this._keyManager;
const keyCode = event.keyCode;
const isArrowKey = keyCode === DOWN_ARROW || keyCode === UP_ARROW;
const isTyping = manager.isTyping();
if (isArrowKey && event.altKey) {
// Close the select on ALT + arrow key to match the native <select>
event.preventDefault();
this.close();
// Don't do anything in this case if the user is typing,
// because the typing sequence can include the space key.
} else if (
!isTyping &&
(keyCode === ENTER || keyCode === SPACE) &&
manager.activeItem &&
!hasModifierKey(event)
) {
event.preventDefault();
manager.activeItem._selectViaInteraction();
} else if (!isTyping && this._multiple && keyCode === A && event.ctrlKey) {
event.preventDefault();
const hasDeselectedOptions = this.options.some(opt => !opt.disabled && !opt.selected);
this.options.forEach(option => {
if (!option.disabled) {
hasDeselectedOptions ? option.select() : option.deselect();
}
});
} else {
const previouslyFocusedIndex = manager.activeItemIndex;
manager.onKeydown(event);