-
Notifications
You must be signed in to change notification settings - Fork 6.7k
/
select.ts
1459 lines (1239 loc) · 50.8 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.io/license
*/
import {ActiveDescendantKeyManager, LiveAnnouncer} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {
BooleanInput,
coerceBooleanProperty,
coerceNumberProperty,
NumberInput
} from '@angular/cdk/coercion';
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,
ConnectedPosition,
Overlay,
ScrollStrategy,
} from '@angular/cdk/overlay';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
AfterContentInit,
Attribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
Directive,
DoCheck,
ElementRef,
EventEmitter,
Inject,
InjectionToken,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
Self,
SimpleChanges,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {ControlValueAccessor, FormGroupDirective, NgControl, NgForm} from '@angular/forms';
import {
_countGroupLabelsBeforeOption,
_getOptionScrollPosition,
CanDisable,
CanDisableRipple,
CanUpdateErrorState,
ErrorStateMatcher,
HasTabIndex,
MAT_OPTGROUP,
MAT_OPTION_PARENT_COMPONENT,
MatOptgroup,
MatOption,
MatOptionSelectionChange,
mixinDisabled,
mixinDisableRipple,
mixinErrorState,
mixinTabIndex,
_MatOptionBase,
} 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';
let nextUniqueId = 0;
/**
* The following style constants are necessary to save here in order
* to properly calculate the alignment of the selected option over
* the trigger element.
*/
/** The max height of the select's overlay panel. */
export const SELECT_PANEL_MAX_HEIGHT = 256;
/** The panel's padding on the x-axis. */
export const SELECT_PANEL_PADDING_X = 16;
/** The panel's x axis padding if it is indented (e.g. there is an option group). */
export const SELECT_PANEL_INDENT_PADDING_X = SELECT_PANEL_PADDING_X * 2;
/** The height of the select items in `em` units. */
export const SELECT_ITEM_HEIGHT_EM = 3;
// TODO(josephperrott): Revert to a constant after 2018 spec updates are fully merged.
/**
* Distance between the panel edge and the option text in
* multi-selection mode.
*
* Calculated as:
* (SELECT_PANEL_PADDING_X * 1.5) + 16 = 40
* The padding is multiplied by 1.5 because the checkbox's margin is half the padding.
* The checkbox width is 16px.
*/
export const SELECT_MULTIPLE_PANEL_PADDING_X = SELECT_PANEL_PADDING_X * 1.5 + 16;
/**
* The select panel will only "fit" inside the viewport if it is positioned at
* this value or more away from the viewport boundary.
*/
export const SELECT_PANEL_VIEWPORT_PADDING = 8;
/** 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');
/** @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[];
}
/** 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,
};
/** 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) { }
}
// Boilerplate for applying mixins to MatSelect.
/** @docs-private */
const _MatSelectMixinBase =
mixinDisableRipple(mixinTabIndex(mixinDisabled(mixinErrorState(class {
constructor(public _elementRef: ElementRef,
public _defaultErrorStateMatcher: ErrorStateMatcher,
public _parentForm: NgForm,
public _parentFormGroup: FormGroupDirective,
public ngControl: NgControl) {}
}))));
/**
* 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');
/**
* Allows the user to customize the trigger that is displayed when the select has a value.
*/
@Directive({
selector: 'mat-select-trigger',
providers: [{provide: MAT_SELECT_TRIGGER, useExisting: MatSelectTrigger}],
})
export class MatSelectTrigger {}
/** Base class with all of the `MatSelect` functionality. */
@Directive()
export abstract class _MatSelectBase<C> extends _MatSelectMixinBase implements AfterContentInit,
OnChanges, OnDestroy, OnInit, DoCheck, ControlValueAccessor, CanDisable, HasTabIndex,
MatFormFieldControl<any>, CanUpdateErrorState, CanDisableRipple {
/** All of the defined select options. */
abstract options: QueryList<_MatOptionBase>;
// 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. */
abstract optionGroups: QueryList<MatOptgroup>;
/** User-supplied override of the trigger element. */
abstract customTrigger: {};
/**
* 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.
*/
abstract _positions: ConnectedPosition[];
/** Scrolls a particular option into the view. */
protected abstract _scrollOptionIntoView(index: number): void;
/** Called when the panel has been opened and the overlay has settled on its final position. */
protected abstract _positioningSettled(): void;
/** Creates a change event object that should be emitted by the select. */
protected abstract _getChangeEvent(value: any): C;
/** Factory function used to create a scroll strategy for this select. */
private _scrollStrategyFactory: () => ScrollStrategy;
/** 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 = `mat-select-${nextUniqueId++}`;
/** Current `ariar-labelledby` value for the select trigger. */
private _triggerAriaLabelledBy: string | null = null;
/** Emits whenever the component is destroyed. */
protected readonly _destroy = new Subject<void>();
/** The aria-describedby attribute on the select for improved a11y. */
_ariaDescribedby: string;
/** Deals with the selection logic. */
_selectionModel: SelectionModel<MatOption>;
/** Manages keyboard events for options in the panel. */
_keyManager: ActiveDescendantKeyManager<MatOption>;
/** `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 = `mat-select-value-${nextUniqueId++}`;
/** 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};
/** 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()
get required(): boolean { return this._required; }
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
private _required: boolean = false;
/** Whether the user should be allowed to select multiple options. */
@Input()
get multiple(): boolean { return this._multiple; }
set multiple(value: boolean) {
if (this._selectionModel && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectDynamicMultipleError();
}
this._multiple = coerceBooleanProperty(value);
}
private _multiple: boolean = false;
/** Whether to center the active option over the trigger. */
@Input()
get disableOptionCentering(): boolean { return this._disableOptionCentering; }
set disableOptionCentering(value: boolean) {
this._disableOptionCentering = coerceBooleanProperty(value);
}
private _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) {
// Always re-assign an array, because it might have been mutated.
if (newValue !== this._value || (this._multiple && Array.isArray(newValue))) {
if (this.options) {
this._setSelectionByValue(newValue);
}
this._value = 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() override errorStateMatcher: ErrorStateMatcher;
/** Time to wait in milliseconds after the last keystroke before moving focus to an item. */
@Input()
get typeaheadDebounceInterval(): number { return this._typeaheadDebounceInterval; }
set typeaheadDebounceInterval(value: number) {
this._typeaheadDebounceInterval = coerceNumberProperty(value);
}
private _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;
/** 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._ngZone.onStable
.pipe(take(1), switchMap(() => this.optionSelectionChanges));
}) as Observable<MatOptionSelectionChange>;
/** 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: EventEmitter<C> = new EventEmitter<C>();
/**
* 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(
protected _viewportRuler: ViewportRuler,
protected _changeDetectorRef: ChangeDetectorRef,
protected _ngZone: NgZone,
_defaultErrorStateMatcher: ErrorStateMatcher,
elementRef: ElementRef,
@Optional() private _dir: Directionality,
@Optional() _parentForm: NgForm,
@Optional() _parentFormGroup: FormGroupDirective,
@Optional() @Inject(MAT_FORM_FIELD) protected _parentFormField: MatFormField,
@Self() @Optional() ngControl: NgControl,
@Attribute('tabindex') tabIndex: string,
@Inject(MAT_SELECT_SCROLL_STRATEGY) scrollStrategyFactory: any,
private _liveAnnouncer: LiveAnnouncer,
@Optional() @Inject(MAT_SELECT_CONFIG) private _defaultOptions?: MatSelectConfig) {
super(elementRef, _defaultErrorStateMatcher, _parentForm,
_parentFormGroup, ngControl);
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 (_defaultOptions?.typeaheadDebounceInterval != null) {
this._typeaheadDebounceInterval = _defaultOptions.typeaheadDebounceInterval;
}
this._scrollStrategyFactory = scrollStrategyFactory;
this._scrollStrategy = this._scrollStrategyFactory();
this.tabIndex = 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));
}
ngAfterContentInit() {
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();
// 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 (this.ngControl) {
this.updateErrorState();
}
}
ngOnChanges(changes: SimpleChanges) {
// Updating the disabled state is handled by `mixinDisabled`, but we need to additionally let
// the parent form field know to run change detection when the disabled state changes.
if (changes['disabled']) {
this.stateChanges.next();
}
if (changes['typeaheadDebounceInterval'] && this._keyManager) {
this._keyManager.withTypeAhead(this._typeaheadDebounceInterval);
}
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
this.stateChanges.complete();
}
/** Toggles the overlay panel open or closed. */
toggle(): void {
this.panelOpen ? this.close() : this.open();
}
/** Opens the overlay panel. */
open(): void {
if (this._canOpen()) {
this._panelOpen = true;
this._keyManager.withHorizontalOrientation(null);
this._highlightCorrectOption();
this._changeDetectorRef.markForCheck();
}
}
/** 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();
}
}
/**
* 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.value = 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;
}
/** 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);
if (this._multiple && isArrowKey && event.shiftKey && manager.activeItem &&
manager.activeItemIndex !== previouslyFocusedIndex) {
manager.activeItem._selectViaInteraction();
}
}
}
_onFocus() {
if (!this.disabled) {
this._focused = true;
this.stateChanges.next();
}
}
/**
* Calls the touched callback only if the panel is closed. Otherwise, the trigger will
* "blur" to the panel when it opens, causing a false positive.
*/
_onBlur() {
this._focused = false;
if (!this.disabled && !this.panelOpen) {
this._onTouched();
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
}
}
/**
* Callback that is invoked when the overlay panel has been attached.
*/
_onAttached(): void {
this._overlayDir.positionChange.pipe(take(1)).subscribe(() => {
this._changeDetectorRef.detectChanges();
this._positioningSettled();
});
}
/** Returns the theme to be used on the panel. */
_getPanelTheme(): string {
return this._parentFormField ? `mat-${this._parentFormField.color}` : '';
}
/** Whether the select has a value. */
get empty(): boolean {
return !this._selectionModel || this._selectionModel.isEmpty();
}
private _initializeSelection(): void {
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
this._setSelectionByValue(this.ngControl ? this.ngControl.value : this._value);
this.stateChanges.next();
});
}
/**
* Sets the selected option based on a value. If no option can be
* found with the designated value, the select trigger is cleared.
*/
private _setSelectionByValue(value: any | any[]): void {
this._selectionModel.selected.forEach(option => option.setInactiveStyles());
this._selectionModel.clear();
if (this.multiple && value) {
if (!Array.isArray(value) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectNonArrayValueError();
}
value.forEach((currentValue: any) => this._selectValue(currentValue));
this._sortValues();
} else {
const correspondingOption = this._selectValue(value);
// Shift focus to the active item. Note that we shouldn't do this in multiple
// mode, because we don't know what option the user interacted with last.
if (correspondingOption) {
this._keyManager.updateActiveItem(correspondingOption);
} else if (!this.panelOpen) {
// Otherwise reset the highlighted option. Note that we only want to do this while
// closed, because doing it while open can shift the user's focus unnecessarily.
this._keyManager.updateActiveItem(-1);
}
}
this._changeDetectorRef.markForCheck();
}
/**
* Finds and selects and option based on its value.
* @returns Option that has the corresponding value.
*/
private _selectValue(value: any): MatOption | undefined {
const correspondingOption = this.options.find((option: MatOption) => {
// Skip options that are already in the model. This allows us to handle cases
// where the same primitive value is selected multiple times.
if (this._selectionModel.isSelected(option)) {
return false;
}
try {
// Treat null as a special reset value.
return option.value != null && this._compareWith(option.value, value);
} catch (error) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
// Notify developers of errors in their comparator.
console.warn(error);
}
return false;
}
});
if (correspondingOption) {
this._selectionModel.select(correspondingOption);
}
return correspondingOption;
}
/** Sets up a key manager to listen to keyboard events on the overlay panel. */
private _initKeyManager() {
this._keyManager = new ActiveDescendantKeyManager<MatOption>(this.options)
.withTypeAhead(this._typeaheadDebounceInterval)
.withVerticalOrientation()
.withHorizontalOrientation(this._isRtl() ? 'rtl' : 'ltr')
.withHomeAndEnd()
.withAllowedModifierKeys(['shiftKey']);
this._keyManager.tabOut.pipe(takeUntil(this._destroy)).subscribe(() => {
if (this.panelOpen) {
// Select the active item when tabbing away. This is consistent with how the native
// select behaves. Note that we only want to do this in single selection mode.
if (!this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
// Restore focus to the trigger before closing. Ensures that the focus
// position won't be lost if the user got focus into the overlay.
this.focus();
this.close();
}
});
this._keyManager.change.pipe(takeUntil(this._destroy)).subscribe(() => {
if (this._panelOpen && this.panel) {
this._scrollOptionIntoView(this._keyManager.activeItemIndex || 0);
} else if (!this._panelOpen && !this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
});
}
/** Drops current option subscriptions and IDs and resets from scratch. */
private _resetOptions(): void {
const changedOrDestroyed = merge(this.options.changes, this._destroy);
this.optionSelectionChanges.pipe(takeUntil(changedOrDestroyed)).subscribe(event => {
this._onSelect(event.source, event.isUserInput);
if (event.isUserInput && !this.multiple && this._panelOpen) {
this.close();
this.focus();
}
});
// Listen to changes in the internal state of the options and react accordingly.
// Handles cases like the labels of the selected options changing.
merge(...this.options.map(option => option._stateChanges))
.pipe(takeUntil(changedOrDestroyed))
.subscribe(() => {
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
});
}
/** Invoked when an option is clicked. */
private _onSelect(option: MatOption, isUserInput: boolean): void {
const wasSelected = this._selectionModel.isSelected(option);
if (option.value == null && !this._multiple) {
option.deselect();
this._selectionModel.clear();
if (this.value != null) {
this._propagateChanges(option.value);
}
} else {
if (wasSelected !== option.selected) {
option.selected ? this._selectionModel.select(option) :
this._selectionModel.deselect(option);
}
if (isUserInput) {
this._keyManager.setActiveItem(option);
}
if (this.multiple) {
this._sortValues();
if (isUserInput) {
// In case the user selected the option with their mouse, we
// want to restore focus back to the trigger, in order to
// prevent the select keyboard controls from clashing with
// the ones from `mat-option`.
this.focus();
}
}
}
if (wasSelected !== this._selectionModel.isSelected(option)) {
this._propagateChanges();
}
this.stateChanges.next();
}
/** Sorts the selected values in the selected based on their order in the panel. */
private _sortValues() {
if (this.multiple) {
const options = this.options.toArray();
this._selectionModel.sort((a, b) => {
return this.sortComparator ? this.sortComparator(a, b, options) :
options.indexOf(a) - options.indexOf(b);
});
this.stateChanges.next();
}
}
/** Emits change event to set the model value. */
private _propagateChanges(fallbackValue?: any): void {
let valueToEmit: any = null;
if (this.multiple) {
valueToEmit = (this.selected as MatOption[]).map(option => option.value);
} else {
valueToEmit = this.selected ? (this.selected as MatOption).value : fallbackValue;
}
this._value = valueToEmit;
this.valueChange.emit(valueToEmit);
this._onChange(valueToEmit);
this.selectionChange.emit(this._getChangeEvent(valueToEmit));
this._changeDetectorRef.markForCheck();
}
/**
* Highlights the selected item. If no option is selected, it will highlight
* the first item instead.
*/
private _highlightCorrectOption(): void {
if (this._keyManager) {
if (this.empty) {
this._keyManager.setFirstItemActive();
} else {
this._keyManager.setActiveItem(this._selectionModel.selected[0]);
}
}
}
/** Whether the panel is allowed to open. */
protected _canOpen(): boolean {
return !this._panelOpen && !this.disabled && this.options?.length > 0;
}
/** Focuses the select element. */
focus(options?: FocusOptions): void {
this._elementRef.nativeElement.focus(options);
}
/** Gets the aria-labelledby for the select panel. */
_getPanelAriaLabelledby(): string | null {
if (this.ariaLabel) {
return null;
}
const labelId = this._parentFormField?.getLabelId();
const labelExpression = (labelId ? labelId + ' ' : '');
return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId;
}