/
radio.ts
672 lines (582 loc) · 21.3 KB
/
radio.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
/**
* @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 {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y';
import {
BooleanInput,
coerceBooleanProperty,
coerceNumberProperty,
NumberInput,
} from '@angular/cdk/coercion';
import {UniqueSelectionDispatcher} from '@angular/cdk/collections';
import {
AfterContentInit,
AfterViewInit,
Attribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Inject,
InjectionToken,
Input,
OnDestroy,
OnInit,
Optional,
Output,
QueryList,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {
CanDisableRipple,
CanDisableRippleCtor,
HasTabIndex,
HasTabIndexCtor,
mixinDisableRipple,
mixinTabIndex,
ThemePalette,
} from '@angular/material/core';
import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations';
export interface MatRadioDefaultOptions {
color: ThemePalette;
}
export const MAT_RADIO_DEFAULT_OPTIONS =
new InjectionToken<MatRadioDefaultOptions>('mat-radio-default-options', {
providedIn: 'root',
factory: MAT_RADIO_DEFAULT_OPTIONS_FACTORY
});
export function MAT_RADIO_DEFAULT_OPTIONS_FACTORY(): MatRadioDefaultOptions {
return {
color: 'accent'
};
}
// Increasing integer for generating unique ids for radio components.
let nextUniqueId = 0;
/**
* Provider Expression that allows mat-radio-group to register as a ControlValueAccessor. This
* allows it to support [(ngModel)] and ngControl.
* @docs-private
*/
export const MAT_RADIO_GROUP_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatRadioGroup),
multi: true
};
/** Change event object emitted by MatRadio and MatRadioGroup. */
export class MatRadioChange {
constructor(
/** The MatRadioButton that emits the change event. */
public source: _MatRadioButtonBase,
/** The value of the MatRadioButton. */
public value: any) {}
}
/**
* Injection token that can be used to inject instances of `MatRadioGroup`. It serves as
* alternative token to the actual `MatRadioGroup` class which could cause unnecessary
* retention of the class and its component metadata.
*/
export const MAT_RADIO_GROUP =
new InjectionToken<_MatRadioGroupBase<_MatRadioButtonBase>>('MatRadioGroup');
/**
* Base class with all of the `MatRadioGroup` functionality.
* @docs-private
*/
@Directive()
export abstract class _MatRadioGroupBase<T extends _MatRadioButtonBase> implements AfterContentInit,
ControlValueAccessor {
/** Selected value for the radio group. */
private _value: any = null;
/** The HTML name attribute applied to radio buttons in this group. */
private _name: string = `mat-radio-group-${nextUniqueId++}`;
/** The currently selected radio button. Should match value. */
private _selected: T | null = null;
/** Whether the `value` has been set to its initial value. */
private _isInitialized: boolean = false;
/** Whether the labels should appear after or before the radio-buttons. Defaults to 'after' */
private _labelPosition: 'before' | 'after' = 'after';
/** Whether the radio group is disabled. */
private _disabled: boolean = false;
/** Whether the radio group is required. */
private _required: boolean = false;
/** The method to be called in order to update ngModel */
_controlValueAccessorChangeFn: (value: any) => void = () => {};
/**
* onTouch function registered via registerOnTouch (ControlValueAccessor).
* @docs-private
*/
onTouched: () => any = () => {};
/**
* Event emitted when the group value changes.
* Change events are only emitted when the value changes due to user interaction with
* a radio button (the same behavior as `<input type-"radio">`).
*/
@Output() readonly change: EventEmitter<MatRadioChange> = new EventEmitter<MatRadioChange>();
/** Child radio buttons. */
abstract _radios: QueryList<T>;
/** Theme color for all of the radio buttons in the group. */
@Input() color: ThemePalette;
/** Name of the radio button group. All radio buttons inside this group will use this name. */
@Input()
get name(): string { return this._name; }
set name(value: string) {
this._name = value;
this._updateRadioButtonNames();
}
/** Whether the labels should appear after or before the radio-buttons. Defaults to 'after' */
@Input()
get labelPosition(): 'before' | 'after' {
return this._labelPosition;
}
set labelPosition(v) {
this._labelPosition = v === 'before' ? 'before' : 'after';
this._markRadiosForCheck();
}
/**
* Value for the radio-group. Should equal the value of the selected radio button if there is
* a corresponding radio button with a matching value. If there is not such a corresponding
* radio button, this value persists to be applied in case a new radio button is added with a
* matching value.
*/
@Input()
get value(): any { return this._value; }
set value(newValue: any) {
if (this._value !== newValue) {
// Set this before proceeding to ensure no circular loop occurs with selection.
this._value = newValue;
this._updateSelectedRadioFromValue();
this._checkSelectedRadioButton();
}
}
_checkSelectedRadioButton() {
if (this._selected && !this._selected.checked) {
this._selected.checked = true;
}
}
/**
* The currently selected radio button. If set to a new radio button, the radio group value
* will be updated to match the new selected button.
*/
@Input()
get selected() { return this._selected; }
set selected(selected: T | null) {
this._selected = selected;
this.value = selected ? selected.value : null;
this._checkSelectedRadioButton();
}
/** Whether the radio group is disabled */
@Input()
get disabled(): boolean { return this._disabled; }
set disabled(value) {
this._disabled = coerceBooleanProperty(value);
this._markRadiosForCheck();
}
/** Whether the radio group is required */
@Input()
get required(): boolean { return this._required; }
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
this._markRadiosForCheck();
}
constructor(private _changeDetector: ChangeDetectorRef) { }
/**
* Initialize properties once content children are available.
* This allows us to propagate relevant attributes to associated buttons.
*/
ngAfterContentInit() {
// Mark this component as initialized in AfterContentInit because the initial value can
// possibly be set by NgModel on MatRadioGroup, and it is possible that the OnInit of the
// NgModel occurs *after* the OnInit of the MatRadioGroup.
this._isInitialized = true;
}
/**
* Mark this group as being "touched" (for ngModel). Meant to be called by the contained
* radio buttons upon their blur.
*/
_touch() {
if (this.onTouched) {
this.onTouched();
}
}
private _updateRadioButtonNames(): void {
if (this._radios) {
this._radios.forEach(radio => {
radio.name = this.name;
radio._markForCheck();
});
}
}
/** Updates the `selected` radio button from the internal _value state. */
private _updateSelectedRadioFromValue(): void {
// If the value already matches the selected radio, do nothing.
const isAlreadySelected = this._selected !== null && this._selected.value === this._value;
if (this._radios && !isAlreadySelected) {
this._selected = null;
this._radios.forEach(radio => {
radio.checked = this.value === radio.value;
if (radio.checked) {
this._selected = radio;
}
});
}
}
/** Dispatch change event with current selection and group value. */
_emitChangeEvent(): void {
if (this._isInitialized) {
this.change.emit(new MatRadioChange(this._selected!, this._value));
}
}
_markRadiosForCheck() {
if (this._radios) {
this._radios.forEach(radio => radio._markForCheck());
}
}
/**
* Sets the model value. Implemented as part of ControlValueAccessor.
* @param value
*/
writeValue(value: any) {
this.value = value;
this._changeDetector.markForCheck();
}
/**
* Registers a callback to be triggered when the model value changes.
* Implemented as part of ControlValueAccessor.
* @param fn Callback to be registered.
*/
registerOnChange(fn: (value: any) => void) {
this._controlValueAccessorChangeFn = fn;
}
/**
* Registers a callback to be triggered when the control is touched.
* Implemented as part of ControlValueAccessor.
* @param fn Callback to be registered.
*/
registerOnTouched(fn: any) {
this.onTouched = fn;
}
/**
* Sets the disabled state of the control. Implemented as a part of ControlValueAccessor.
* @param isDisabled Whether the control should be disabled.
*/
setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
this._changeDetector.markForCheck();
}
static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_required: BooleanInput;
}
/**
* A group of radio buttons. May contain one or more `<mat-radio-button>` elements.
*/
@Directive({
selector: 'mat-radio-group',
exportAs: 'matRadioGroup',
providers: [
MAT_RADIO_GROUP_CONTROL_VALUE_ACCESSOR,
{provide: MAT_RADIO_GROUP, useExisting: MatRadioGroup},
],
host: {
'role': 'radiogroup',
'class': 'mat-radio-group',
},
})
export class MatRadioGroup extends _MatRadioGroupBase<MatRadioButton> {
@ContentChildren(forwardRef(() => MatRadioButton), {descendants: true})
_radios: QueryList<MatRadioButton>;
}
// Boilerplate for applying mixins to MatRadioButton.
/** @docs-private */
abstract class MatRadioButtonBase {
// Since the disabled property is manually defined for the MatRadioButton and isn't set up in
// the mixin base class. To be able to use the tabindex mixin, a disabled property must be
// defined to properly work.
abstract disabled: boolean;
constructor(public _elementRef: ElementRef) {}
}
// As per Material design specifications the selection control radio should use the accent color
// palette by default. https://material.io/guidelines/components/selection-controls.html
const _MatRadioButtonMixinBase:
CanDisableRippleCtor & HasTabIndexCtor & typeof MatRadioButtonBase =
mixinDisableRipple(mixinTabIndex(MatRadioButtonBase));
/**
* Base class with all of the `MatRadioButton` functionality.
* @docs-private
*/
@Directive()
export abstract class _MatRadioButtonBase extends _MatRadioButtonMixinBase implements OnInit,
AfterViewInit, OnDestroy, CanDisableRipple, HasTabIndex {
private _uniqueId: string = `mat-radio-${++nextUniqueId}`;
/** The unique ID for the radio button. */
@Input() id: string = this._uniqueId;
/** Analog to HTML 'name' attribute used to group radios for unique selection. */
@Input() name: string;
/** Used to set the 'aria-label' attribute on the underlying input element. */
@Input('aria-label') ariaLabel: string;
/** The 'aria-labelledby' attribute takes precedence as the element's text alternative. */
@Input('aria-labelledby') ariaLabelledby: string;
/** The 'aria-describedby' attribute is read after the element's label and field type. */
@Input('aria-describedby') ariaDescribedby: string;
/** Whether this radio button is checked. */
@Input()
get checked(): boolean { return this._checked; }
set checked(value: boolean) {
const newCheckedState = coerceBooleanProperty(value);
if (this._checked !== newCheckedState) {
this._checked = newCheckedState;
if (newCheckedState && this.radioGroup && this.radioGroup.value !== this.value) {
this.radioGroup.selected = this;
} else if (!newCheckedState && this.radioGroup && this.radioGroup.value === this.value) {
// When unchecking the selected radio button, update the selected radio
// property on the group.
this.radioGroup.selected = null;
}
if (newCheckedState) {
// Notify all radio buttons with the same name to un-check.
this._radioDispatcher.notify(this.id, this.name);
}
this._changeDetector.markForCheck();
}
}
/** The value of this radio button. */
@Input()
get value(): any { return this._value; }
set value(value: any) {
if (this._value !== value) {
this._value = value;
if (this.radioGroup !== null) {
if (!this.checked) {
// Update checked when the value changed to match the radio group's value
this.checked = this.radioGroup.value === value;
}
if (this.checked) {
this.radioGroup.selected = this;
}
}
}
}
/** Whether the label should appear after or before the radio button. Defaults to 'after' */
@Input()
get labelPosition(): 'before' | 'after' {
return this._labelPosition || (this.radioGroup && this.radioGroup.labelPosition) || 'after';
}
set labelPosition(value) {
this._labelPosition = value;
}
private _labelPosition: 'before' | 'after';
/** Whether the radio button is disabled. */
@Input()
get disabled(): boolean {
return this._disabled || (this.radioGroup !== null && this.radioGroup.disabled);
}
set disabled(value: boolean) {
this._setDisabled(coerceBooleanProperty(value));
}
/** Whether the radio button is required. */
@Input()
get required(): boolean {
return this._required || (this.radioGroup && this.radioGroup.required);
}
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
}
/** Theme color of the radio button. */
@Input()
get color(): ThemePalette {
return this._color ||
(this.radioGroup && this.radioGroup.color) ||
this._providerOverride && this._providerOverride.color || 'accent';
}
set color(newValue: ThemePalette) { this._color = newValue; }
private _color: ThemePalette;
/**
* Event emitted when the checked state of this radio button changes.
* Change events are only emitted when the value changes due to user interaction with
* the radio button (the same behavior as `<input type-"radio">`).
*/
@Output() readonly change: EventEmitter<MatRadioChange> = new EventEmitter<MatRadioChange>();
/** The parent radio group. May or may not be present. */
radioGroup: _MatRadioGroupBase<_MatRadioButtonBase>;
/** ID of the native input element inside `<mat-radio-button>` */
get inputId(): string { return `${this.id || this._uniqueId}-input`; }
/** Whether this radio is checked. */
private _checked: boolean = false;
/** Whether this radio is disabled. */
private _disabled: boolean;
/** Whether this radio is required. */
private _required: boolean;
/** Value assigned to this radio. */
private _value: any = null;
/** Unregister function for _radioDispatcher */
private _removeUniqueSelectionListener: () => void = () => {};
/** The native `<input type=radio>` element */
@ViewChild('input') _inputElement: ElementRef<HTMLInputElement>;
/** Whether animations are disabled. */
_noopAnimations: boolean;
constructor(radioGroup: _MatRadioGroupBase<_MatRadioButtonBase>,
elementRef: ElementRef,
protected _changeDetector: ChangeDetectorRef,
private _focusMonitor: FocusMonitor,
private _radioDispatcher: UniqueSelectionDispatcher,
animationMode?: string,
private _providerOverride?: MatRadioDefaultOptions,
tabIndex?: string) {
super(elementRef);
// Assertions. Ideally these should be stripped out by the compiler.
// TODO(jelbourn): Assert that there's no name binding AND a parent radio group.
this.radioGroup = radioGroup;
this._noopAnimations = animationMode === 'NoopAnimations';
if (tabIndex) {
this.tabIndex = coerceNumberProperty(tabIndex, 0);
}
this._removeUniqueSelectionListener =
_radioDispatcher.listen((id: string, name: string) => {
if (id !== this.id && name === this.name) {
this.checked = false;
}
});
}
/** Focuses the radio button. */
focus(options?: FocusOptions, origin?: FocusOrigin): void {
if (origin) {
this._focusMonitor.focusVia(this._inputElement, origin, options);
} else {
this._inputElement.nativeElement.focus(options);
}
}
/**
* Marks the radio button as needing checking for change detection.
* This method is exposed because the parent radio group will directly
* update bound properties of the radio button.
*/
_markForCheck() {
// When group value changes, the button will not be notified. Use `markForCheck` to explicit
// update radio button's status
this._changeDetector.markForCheck();
}
ngOnInit() {
if (this.radioGroup) {
// If the radio is inside a radio group, determine if it should be checked
this.checked = this.radioGroup.value === this._value;
if (this.checked) {
this.radioGroup.selected = this;
}
// Copy name from parent radio group
this.name = this.radioGroup.name;
}
}
ngAfterViewInit() {
this._focusMonitor
.monitor(this._elementRef, true)
.subscribe(focusOrigin => {
if (!focusOrigin && this.radioGroup) {
this.radioGroup._touch();
}
});
}
ngOnDestroy() {
this._focusMonitor.stopMonitoring(this._elementRef);
this._removeUniqueSelectionListener();
}
/** Dispatch change event with current value. */
private _emitChangeEvent(): void {
this.change.emit(new MatRadioChange(this, this._value));
}
_isRippleDisabled() {
return this.disableRipple || this.disabled;
}
_onInputClick(event: Event) {
// We have to stop propagation for click events on the visual hidden input element.
// By default, when a user clicks on a label element, a generated click event will be
// dispatched on the associated input element. Since we are using a label element as our
// root container, the click event on the `radio-button` will be executed twice.
// The real click event will bubble up, and the generated click event also tries to bubble up.
// This will lead to multiple click events.
// Preventing bubbling for the second event will solve that issue.
event.stopPropagation();
}
/** Triggered when the radio button receives an interaction from the user. */
_onInputInteraction(event: Event) {
// We always have to stop propagation on the change event.
// Otherwise the change event, from the input element, will bubble up and
// emit its event object to the `change` output.
event.stopPropagation();
if (!this.checked && !this.disabled) {
const groupValueChanged = this.radioGroup && this.value !== this.radioGroup.value;
this.checked = true;
this._emitChangeEvent();
if (this.radioGroup) {
this.radioGroup._controlValueAccessorChangeFn(this.value);
if (groupValueChanged) {
this.radioGroup._emitChangeEvent();
}
}
}
}
/** Sets the disabled state and marks for check if a change occurred. */
protected _setDisabled(value: boolean) {
if (this._disabled !== value) {
this._disabled = value;
this._changeDetector.markForCheck();
}
}
static ngAcceptInputType_checked: BooleanInput;
static ngAcceptInputType_disabled: BooleanInput;
static ngAcceptInputType_required: BooleanInput;
static ngAcceptInputType_disableRipple: BooleanInput;
static ngAcceptInputType_tabIndex: NumberInput;
}
/**
* A Material design radio-button. Typically placed inside of `<mat-radio-group>` elements.
*/
@Component({
selector: 'mat-radio-button',
templateUrl: 'radio.html',
styleUrls: ['radio.css'],
inputs: ['disableRipple', 'tabIndex'],
encapsulation: ViewEncapsulation.None,
exportAs: 'matRadioButton',
host: {
'class': 'mat-radio-button',
'[class.mat-radio-checked]': 'checked',
'[class.mat-radio-disabled]': 'disabled',
'[class._mat-animation-noopable]': '_noopAnimations',
'[class.mat-primary]': 'color === "primary"',
'[class.mat-accent]': 'color === "accent"',
'[class.mat-warn]': 'color === "warn"',
// Needs to be removed since it causes some a11y issues (see #21266).
'[attr.tabindex]': 'null',
'[attr.id]': 'id',
'[attr.aria-label]': 'null',
'[attr.aria-labelledby]': 'null',
'[attr.aria-describedby]': 'null',
// Note: under normal conditions focus shouldn't land on this element, however it may be
// programmatically set, for example inside of a focus trap, in this case we want to forward
// the focus to the native element.
'(focus)': '_inputElement.nativeElement.focus()',
},
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatRadioButton extends _MatRadioButtonBase {
constructor(@Optional() @Inject(MAT_RADIO_GROUP) radioGroup: MatRadioGroup,
elementRef: ElementRef,
changeDetector: ChangeDetectorRef,
focusMonitor: FocusMonitor,
radioDispatcher: UniqueSelectionDispatcher,
@Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode?: string,
@Optional() @Inject(MAT_RADIO_DEFAULT_OPTIONS)
providerOverride?: MatRadioDefaultOptions,
@Attribute('tabindex') tabIndex?: string) {
super(radioGroup, elementRef, changeDetector, focusMonitor, radioDispatcher,
animationMode, providerOverride, tabIndex);
}
}