Skip to content

Commit 15be464

Browse files
committed
fix(select): consistent error behavior to md-input-container
* Gets `md-select` to behave in the same way as `md-input-container` when it comes to errors. This means highlighting itself when it is invalid and touched, or one of the parent forms/form groups is submitted. * Moves the error state logic into a separate function in order to avoid some hard-to-follow selectors and to potentially allow overrides. This should also be a first step to supporting `md-error` inside `md-select`. * Changes the required asterisk to always have the theme warn color, similarly to the input asterisk. Fixes #4611.
1 parent 374aaff commit 15be464

File tree

3 files changed

+124
-11
lines changed

3 files changed

+124
-11
lines changed

src/lib/select/_select-theme.scss

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,7 @@
6666
}
6767
}
6868

69-
.mat-select:focus:not(.mat-select-disabled).mat-warn,
70-
.mat-select:not(:focus).ng-invalid.ng-touched:not(.mat-select-disabled) {
69+
.mat-select:focus:not(.mat-select-disabled).mat-warn, .mat-select-invalid {
7170
@include _mat-select-inner-content-theme($warn);
7271
}
7372
}

src/lib/select/select.spec.ts

Lines changed: 107 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import {TestBed, async, ComponentFixture, fakeAsync, tick, inject} from '@angular/core/testing';
2-
import {By} from '@angular/platform-browser';
31
import {
42
Component,
53
DebugElement,
@@ -9,17 +7,26 @@ import {
97
ChangeDetectionStrategy,
108
OnInit,
119
} from '@angular/core';
10+
import {
11+
ControlValueAccessor,
12+
FormControl,
13+
FormsModule,
14+
NG_VALUE_ACCESSOR,
15+
ReactiveFormsModule,
16+
FormGroup,
17+
FormGroupDirective,
18+
Validators,
19+
} from '@angular/forms';
20+
import {By} from '@angular/platform-browser';
1221
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
22+
import {TestBed, async, ComponentFixture, fakeAsync, tick, inject} from '@angular/core/testing';
1323
import {MdSelectModule} from './index';
1424
import {OverlayContainer} from '../core/overlay/overlay-container';
1525
import {MdSelect} from './select';
1626
import {getMdSelectDynamicMultipleError, getMdSelectNonArrayValueError} from './select-errors';
1727
import {MdOption} from '../core/option/option';
1828
import {Directionality} from '../core/bidi/index';
1929
import {DOWN_ARROW, UP_ARROW, ENTER, SPACE, HOME, END, TAB} from '../core/keyboard/keycodes';
20-
import {
21-
ControlValueAccessor, FormControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule
22-
} from '@angular/forms';
2330
import {Subject} from 'rxjs/Subject';
2431
import {ViewportRuler} from '../core/overlay/position/viewport-ruler';
2532
import {dispatchFakeEvent, dispatchKeyboardEvent, wrappedErrorMessage} from '@angular/cdk/testing';
@@ -63,7 +70,8 @@ describe('MdSelect', () => {
6370
ResetValuesSelect,
6471
FalsyValueSelect,
6572
SelectWithGroups,
66-
InvalidSelectInForm
73+
InvalidSelectInForm,
74+
SelectInsideFormGroup
6775
],
6876
providers: [
6977
{provide: OverlayContainer, useFactory: () => {
@@ -1584,11 +1592,12 @@ describe('MdSelect', () => {
15841592
'mat-select-required', `Expected the mat-select-required class to be set.`);
15851593
});
15861594

1587-
it('should set aria-invalid for selects that are invalid', () => {
1595+
it('should set aria-invalid for selects that are invalid and touched', () => {
15881596
expect(select.getAttribute('aria-invalid'))
15891597
.toEqual('false', `Expected aria-invalid attr to be false for valid selects.`);
15901598

15911599
fixture.componentInstance.isRequired = true;
1600+
fixture.componentInstance.control.markAsTouched();
15921601
fixture.detectChanges();
15931602

15941603
expect(select.getAttribute('aria-invalid'))
@@ -2437,6 +2446,77 @@ describe('MdSelect', () => {
24372446

24382447
});
24392448

2449+
describe('error state', () => {
2450+
let fixture: ComponentFixture<SelectInsideFormGroup>;
2451+
let testComponent: SelectInsideFormGroup;
2452+
let select: HTMLElement;
2453+
2454+
beforeEach(() => {
2455+
fixture = TestBed.createComponent(SelectInsideFormGroup);
2456+
fixture.detectChanges();
2457+
testComponent = fixture.componentInstance;
2458+
select = fixture.debugElement.query(By.css('md-select')).nativeElement;
2459+
});
2460+
2461+
it('should not set the invalid class on a clean select', () => {
2462+
expect(testComponent.formGroup.untouched).toBe(true, 'Expected the form to be untouched.');
2463+
expect(testComponent.formControl.invalid).toBe(true, 'Expected form control to be invalid.');
2464+
expect(select.classList)
2465+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2466+
expect(select.getAttribute('aria-invalid'))
2467+
.toBe('false', 'Expected aria-invalid to be set to false.');
2468+
});
2469+
2470+
it('should appear as invalid if it becomes touched', () => {
2471+
expect(select.classList)
2472+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2473+
expect(select.getAttribute('aria-invalid'))
2474+
.toBe('false', 'Expected aria-invalid to be set to false.');
2475+
2476+
testComponent.formControl.markAsTouched();
2477+
fixture.detectChanges();
2478+
2479+
expect(select.classList)
2480+
.toContain('mat-select-invalid', 'Expected select to appear invalid.');
2481+
expect(select.getAttribute('aria-invalid'))
2482+
.toBe('true', 'Expected aria-invalid to be set to true.');
2483+
});
2484+
2485+
it('should not have the invalid class when the select becomes valid', () => {
2486+
testComponent.formControl.markAsTouched();
2487+
fixture.detectChanges();
2488+
2489+
expect(select.classList)
2490+
.toContain('mat-select-invalid', 'Expected select to appear invalid.');
2491+
expect(select.getAttribute('aria-invalid'))
2492+
.toBe('true', 'Expected aria-invalid to be set to true.');
2493+
2494+
testComponent.formControl.setValue('pizza-1');
2495+
fixture.detectChanges();
2496+
2497+
expect(select.classList)
2498+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2499+
expect(select.getAttribute('aria-invalid'))
2500+
.toBe('false', 'Expected aria-invalid to be set to false.');
2501+
});
2502+
2503+
it('should appear as invalid when the parent form group is submitted', () => {
2504+
expect(select.classList)
2505+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2506+
expect(select.getAttribute('aria-invalid'))
2507+
.toBe('false', 'Expected aria-invalid to be set to false.');
2508+
2509+
dispatchFakeEvent(fixture.debugElement.query(By.css('form')).nativeElement, 'submit');
2510+
fixture.detectChanges();
2511+
2512+
expect(select.classList)
2513+
.toContain('mat-select-invalid', 'Expected select to appear invalid.');
2514+
expect(select.getAttribute('aria-invalid'))
2515+
.toBe('true', 'Expected aria-invalid to be set to true.');
2516+
});
2517+
2518+
});
2519+
24402520
});
24412521

24422522

@@ -2784,6 +2864,7 @@ class BasicSelectWithTheming {
27842864
theme: string;
27852865
}
27862866

2867+
27872868
@Component({
27882869
selector: 'reset-values-select',
27892870
template: `
@@ -2810,7 +2891,6 @@ class ResetValuesSelect {
28102891
@ViewChild(MdSelect) select: MdSelect;
28112892
}
28122893

2813-
28142894
@Component({
28152895
template: `
28162896
<md-select [formControl]="control">
@@ -2892,3 +2972,22 @@ class SelectWithGroups {
28922972
class InvalidSelectInForm {
28932973
value: any;
28942974
}
2975+
2976+
2977+
@Component({
2978+
template: `
2979+
<form [formGroup]="formGroup">
2980+
<md-select placeholder="Food" formControlName="food">
2981+
<md-option value="steak-0">Steak</md-option>
2982+
<md-option value="pizza-1">Pizza</md-option>
2983+
</md-select>
2984+
</form>
2985+
`
2986+
})
2987+
class SelectInsideFormGroup {
2988+
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
2989+
formControl = new FormControl('', Validators.required);
2990+
formGroup = new FormGroup({
2991+
food: this.formControl
2992+
});
2993+
}

src/lib/select/select.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
ChangeDetectionStrategy,
2929
InjectionToken,
3030
} from '@angular/core';
31+
import {NgForm, FormGroupDirective} from '@angular/forms';
3132
import {MdOption, MdOptionSelectionChange, MdOptgroup} from '../core/option/index';
3233
import {ENTER, SPACE, UP_ARROW, DOWN_ARROW, HOME, END} from '../core/keyboard/keycodes';
3334
import {FocusKeyManager} from '../core/a11y/focus-key-manager';
@@ -153,9 +154,10 @@ export const _MdSelectMixinBase = mixinColor(mixinDisabled(MdSelectBase), 'prima
153154
'[attr.aria-labelledby]': 'ariaLabelledby',
154155
'[attr.aria-required]': 'required.toString()',
155156
'[attr.aria-disabled]': 'disabled.toString()',
156-
'[attr.aria-invalid]': '_control?.invalid || "false"',
157+
'[attr.aria-invalid]': '_isErrorState()',
157158
'[attr.aria-owns]': '_optionIds',
158159
'[class.mat-select-disabled]': 'disabled',
160+
'[class.mat-select-invalid]': '_isErrorState()',
159161
'[class.mat-select-required]': 'required',
160162
'class': 'mat-select',
161163
'(keydown)': '_handleClosedKeydown($event)',
@@ -352,10 +354,13 @@ export class MdSelect extends _MdSelectMixinBase implements AfterContentInit, On
352354
renderer: Renderer2,
353355
elementRef: ElementRef,
354356
@Optional() private _dir: Directionality,
357+
@Optional() private _parentForm: NgForm,
358+
@Optional() private _parentFormGroup: FormGroupDirective,
355359
@Self() @Optional() public _control: NgControl,
356360
@Attribute('tabindex') tabIndex: string,
357361
@Optional() @Inject(MD_PLACEHOLDER_GLOBAL_OPTIONS) placeholderOptions: PlaceholderOptions,
358362
@Inject(MD_SELECT_SCROLL_STRATEGY) private _scrollStrategyFactory) {
363+
359364
super(renderer, elementRef);
360365

361366
if (this._control) {
@@ -589,6 +594,16 @@ export class MdSelect extends _MdSelectMixinBase implements AfterContentInit, On
589594
return this._selectionModel && this._selectionModel.hasValue();
590595
}
591596

597+
/** Whether the select is in an error state. */
598+
_isErrorState(): boolean {
599+
const isInvalid = this._control && this._control.invalid;
600+
const isTouched = this._control && this._control.touched;
601+
const isSubmitted = (this._parentFormGroup && this._parentFormGroup.submitted) ||
602+
(this._parentForm && this._parentForm.submitted);
603+
604+
return !!(isInvalid && (isTouched || isSubmitted));
605+
}
606+
592607
/**
593608
* Sets the scroll position of the scroll container. This must be called after
594609
* the overlay pane is attached or the scroll container element will not yet be

0 commit comments

Comments
 (0)