-
Notifications
You must be signed in to change notification settings - Fork 6.8k
/
select.ts
1335 lines (1141 loc) · 45.6 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 {coerceBooleanProperty} from '@angular/cdk/coercion';
import {SelectionModel} from '@angular/cdk/collections';
import {
A,
DOWN_ARROW,
END,
ENTER,
HOME,
LEFT_ARROW,
RIGHT_ARROW,
SPACE,
UP_ARROW,
hasModifierKey,
} from '@angular/cdk/keycodes';
import {CdkConnectedOverlay, 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,
isDevMode,
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,
CanDisableCtor,
CanDisableRipple,
CanDisableRippleCtor,
CanUpdateErrorState,
CanUpdateErrorStateCtor,
ErrorStateMatcher,
HasTabIndex,
HasTabIndexCtor,
MAT_OPTION_PARENT_COMPONENT,
MatOptgroup,
MatOption,
MatOptionSelectionChange,
mixinDisabled,
mixinDisableRipple,
mixinErrorState,
mixinTabIndex,
} from '@angular/material/core';
import {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) + 20 = 44
* The padding is multiplied by 1.5 because the checkbox's margin is half the padding.
* The checkbox width is 16px.
*/
export let SELECT_MULTIPLE_PANEL_PADDING_X = 0;
/**
* 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();
}
/** @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 */
export class MatSelectBase {
constructor(public _elementRef: ElementRef,
public _defaultErrorStateMatcher: ErrorStateMatcher,
public _parentForm: NgForm,
public _parentFormGroup: FormGroupDirective,
public ngControl: NgControl) {}
}
export const _MatSelectMixinBase:
CanDisableCtor &
HasTabIndexCtor &
CanDisableRippleCtor &
CanUpdateErrorStateCtor &
typeof MatSelectBase =
mixinDisableRipple(mixinTabIndex(mixinDisabled(mixinErrorState(MatSelectBase))));
/**
* Allows the user to customize the trigger that is displayed when the select has a value.
*/
@Directive({
selector: 'mat-select-trigger'
})
export class MatSelectTrigger {}
@Component({
moduleId: module.id,
selector: 'mat-select',
exportAs: 'matSelect',
templateUrl: 'select.html',
styleUrls: ['select.css'],
inputs: ['disabled', 'disableRipple', 'tabIndex'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'role': 'listbox',
'[attr.id]': 'id',
'[attr.tabindex]': 'tabIndex',
'[attr.aria-label]': '_getAriaLabel()',
'[attr.aria-labelledby]': '_getAriaLabelledby()',
'[attr.aria-required]': 'required.toString()',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-invalid]': 'errorState',
'[attr.aria-owns]': 'panelOpen ? _optionIds : null',
'[attr.aria-multiselectable]': 'multiple',
'[attr.aria-describedby]': '_ariaDescribedby || null',
'[attr.aria-activedescendant]': '_getAriaActiveDescendant()',
'[class.mat-select-disabled]': 'disabled',
'[class.mat-select-invalid]': 'errorState',
'[class.mat-select-required]': 'required',
'[class.mat-select-empty]': 'empty',
'class': 'mat-select',
'(keydown)': '_handleKeydown($event)',
'(focus)': '_onFocus()',
'(blur)': '_onBlur()',
},
animations: [
matSelectAnimations.transformPanelWrap,
matSelectAnimations.transformPanel
],
providers: [
{provide: MatFormFieldControl, useExisting: MatSelect},
{provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatSelect}
],
})
export class MatSelect extends _MatSelectMixinBase implements AfterContentInit, OnChanges,
OnDestroy, OnInit, DoCheck, ControlValueAccessor, CanDisable, HasTabIndex,
MatFormFieldControl<any>, CanUpdateErrorState, CanDisableRipple {
private _scrollStrategyFactory: () => ScrollStrategy;
/** Whether or not the overlay panel is open. */
private _panelOpen = false;
/** Whether filling out the select is required in the form. */
private _required: boolean = false;
/** The scroll position of the overlay panel, calculated to center the selected option. */
private _scrollTop = 0;
/** The placeholder displayed in the trigger of the select. */
private _placeholder: string;
/** Whether the component is in multiple selection mode. */
private _multiple: boolean = 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++}`;
/** Emits whenever the component is destroyed. */
private readonly _destroy = new Subject<void>();
/** The last measured value for the trigger's client bounding rect. */
_triggerRect: ClientRect;
/** The aria-describedby attribute on the select for improved a11y. */
_ariaDescribedby: string;
/** The cached font-size of the trigger element. */
_triggerFontSize = 0;
/** 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 = () => {};
/** The IDs of child options to be passed to the aria-owns attribute. */
_optionIds: string = '';
/** The value of the select panel's transform-origin property. */
_transformOrigin: string = 'top';
/** Emits when the panel element is finished transforming in. */
_panelDoneAnimatingStream = new Subject<string>();
/** Strategy that will be used to handle scrolling while the select panel is open. */
_scrollStrategy: ScrollStrategy;
/**
* The y-offset of the overlay panel in relation to the trigger's top start corner.
* This must be adjusted to align the selected option text over the trigger text.
* when the panel opens. Will change based on the y-position of the selected option.
*/
_offsetY = 0;
/**
* 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 = [
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'top',
},
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'bottom',
},
];
/** Whether the component is disabling centering of the active option over the trigger. */
private _disableOptionCentering: boolean = false;
/** Whether the select is focused. */
get focused(): boolean {
return this._focused || this._panelOpen;
}
/**
* @deprecated Setter to be removed as this property is intended to be readonly.
* @breaking-change 8.0.0
*/
set focused(value: boolean) {
this._focused = value;
}
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) overlayDir: CdkConnectedOverlay;
/** All of the defined select options. */
@ContentChildren(MatOption, { descendants: true }) options: QueryList<MatOption>;
/** All of the defined groups of options. */
@ContentChildren(MatOptgroup) optionGroups: QueryList<MatOptgroup>;
/** Classes to be passed to the select panel. Supports the same syntax as `ngClass`. */
@Input() panelClass: string|string[]|Set<string>|{[key: string]: any};
/** User-supplied override of the trigger element. */
@ContentChild(MatSelectTrigger) customTrigger: MatSelectTrigger;
/** 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();
}
/** Whether the component is required. */
@Input()
get required(): boolean { return this._required; }
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this.stateChanges.next();
}
/** Whether the user should be allowed to select multiple options. */
@Input()
get multiple(): boolean { return this._multiple; }
set multiple(value: boolean) {
if (this._selectionModel) {
throw getMatSelectDynamicMultipleError();
}
this._multiple = coerceBooleanProperty(value);
}
/** Whether to center the active option over the trigger. */
@Input()
get disableOptionCentering(): boolean { return this._disableOptionCentering; }
set disableOptionCentering(value: boolean) {
this._disableOptionCentering = coerceBooleanProperty(value);
}
/**
* 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') {
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) {
if (newValue !== this._value) {
this.writeValue(newValue);
this._value = newValue;
}
}
private _value: any;
/** Aria label of the select. If not specified, the placeholder will be used as label. */
@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() errorStateMatcher: ErrorStateMatcher;
/**
* 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(() => {
if (this.options) {
return merge(...this.options.map(option => option.onSelectionChange));
}
return this._ngZone.onStable
.asObservable()
.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<MatSelectChange> =
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(
private _viewportRuler: ViewportRuler,
private _changeDetectorRef: ChangeDetectorRef,
private _ngZone: NgZone,
_defaultErrorStateMatcher: ErrorStateMatcher,
elementRef: ElementRef,
@Optional() private _dir: Directionality,
@Optional() _parentForm: NgForm,
@Optional() _parentFormGroup: FormGroupDirective,
@Optional() private _parentFormField: MatFormField,
@Self() @Optional() public ngControl: NgControl,
@Attribute('tabindex') tabIndex: string,
@Inject(MAT_SELECT_SCROLL_STRATEGY) scrollStrategyFactory: any,
/**
* @deprecated _liveAnnouncer to be turned into a required parameter.
* @breaking-change 8.0.0
*/
private _liveAnnouncer?: LiveAnnouncer) {
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;
}
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(() => {
if (this.panelOpen) {
this._scrollTop = 0;
this.openedChange.emit(true);
} else {
this.openedChange.emit(false);
this.overlayDir.offsetX = 0;
this._changeDetectorRef.markForCheck();
}
});
this._viewportRuler.change()
.pipe(takeUntil(this._destroy))
.subscribe(() => {
if (this._panelOpen) {
this._triggerRect = this.trigger.nativeElement.getBoundingClientRect();
this._changeDetectorRef.markForCheck();
}
});
}
ngAfterContentInit() {
this._initKeyManager();
this._selectionModel.onChange.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() {
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();
}
}
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.disabled || !this.options || !this.options.length || this._panelOpen) {
return;
}
this._triggerRect = this.trigger.nativeElement.getBoundingClientRect();
// Note: The computed font-size will be a string pixel value (e.g. "16px").
// `parseInt` ignores the trailing 'px' and converts this to a number.
this._triggerFontSize = parseInt(getComputedStyle(this.trigger.nativeElement).fontSize || '0');
this._panelOpen = true;
this._keyManager.withHorizontalOrientation(null);
this._calculateOverlayPosition();
this._highlightCorrectOption();
this._changeDetectorRef.markForCheck();
// Set the font size on the panel element once it exists.
this._ngZone.onStable.asObservable().pipe(take(1)).subscribe(() => {
if (this._triggerFontSize && this.overlayDir.overlayRef &&
this.overlayDir.overlayRef.overlayElement) {
this.overlayDir.overlayRef.overlayElement.style.fontSize = `${this._triggerFontSize}px`;
}
});
}
/** 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 {
if (this.options) {
this._setSelectionByValue(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 ((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;
if (keyCode === HOME || keyCode === END) {
keyCode === HOME ? manager.setFirstItemActive() : manager.setLastItemActive();
event.preventDefault();
} else {
manager.onKeydown(event);
}
const selectedOption = this.selected;
// Since the value has changed, we need to announce it ourselves.
// @breaking-change 8.0.0 remove null check for _liveAnnouncer.
if (this._liveAnnouncer && selectedOption && previouslySelectedOption !== selectedOption) {
this._liveAnnouncer.announce((selectedOption as MatOption).viewValue);
}
}
}
/** Handles keyboard events when the selected is open. */
private _handleOpenKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
const isArrowKey = keyCode === DOWN_ARROW || keyCode === UP_ARROW;
const manager = this._keyManager;
if (keyCode === HOME || keyCode === END) {
event.preventDefault();
keyCode === HOME ? manager.setFirstItemActive() : manager.setLastItemActive();
} else if (isArrowKey && event.altKey) {
// Close the select on ALT + arrow key to match the native <select>
event.preventDefault();
this.close();
} else if ((keyCode === ENTER || keyCode === SPACE) && manager.activeItem &&
!hasModifierKey(event)) {
event.preventDefault();
manager.activeItem._selectViaInteraction();
} else if (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._setPseudoCheckboxPaddingSize();
this._changeDetectorRef.detectChanges();
this._calculateOverlayOffsetX();
this.panel.nativeElement.scrollTop = this._scrollTop;
});
}
/** Returns the theme to be used on the panel. */
_getPanelTheme(): string {
return this._parentFormField ? `mat-${this._parentFormField.color}` : '';
}
// TODO(josephperrott): Remove after 2018 spec updates are fully merged.
/** Sets the pseudo checkbox padding size based on the width of the pseudo checkbox. */
private _setPseudoCheckboxPaddingSize() {
if (!SELECT_MULTIPLE_PANEL_PADDING_X && this.multiple) {
const pseudoCheckbox = this.panel.nativeElement.querySelector('.mat-pseudo-checkbox');
if (pseudoCheckbox) {
SELECT_MULTIPLE_PANEL_PADDING_X = SELECT_PANEL_PADDING_X * 1.5 + pseudoCheckbox.offsetWidth;
}
}
}
/** 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 {
if (this.multiple && value) {
if (!Array.isArray(value)) {
throw getMatSelectNonArrayValueError();
}
this._selectionModel.clear();
value.forEach((currentValue: any) => this._selectValue(currentValue));
this._sortValues();
} else {
this._selectionModel.clear();
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.setActiveItem(correspondingOption);
}
}
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) => {
try {
// Treat null as a special reset value.
return option.value != null && this._compareWith(option.value, value);
} catch (error) {
if (isDevMode()) {
// 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()
.withVerticalOrientation()
.withHorizontalOrientation(this._isRtl() ? 'rtl' : 'ltr')
.withAllowedModifierKeys(['shiftKey']);
this._keyManager.tabOut.pipe(takeUntil(this._destroy)).subscribe(() => {
// 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._scrollActiveOptionIntoView();
} 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();
});
this._setOptionIds();
}
/** 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();
this._propagateChanges(option.value);
} else {
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(new MatSelectChange(this, valueToEmit));