Skip to content

Commit 3d8c223

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 3569805 commit 3d8c223

File tree

3 files changed

+126
-11
lines changed

3 files changed

+126
-11
lines changed

src/lib/select/_select-theme.scss

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,13 @@
5151
&.mat-accent {
5252
@include _mat-select-inner-content-theme($accent);
5353
}
54+
55+
.mat-select-placeholder::after {
56+
color: mat-color($warn);
57+
}
5458
}
5559

56-
.mat-select:focus:not(.mat-select-disabled).mat-warn,
57-
.mat-select:not(:focus).ng-invalid.ng-touched:not(.mat-select-disabled) {
60+
.mat-select:focus:not(.mat-select-disabled).mat-warn, .mat-select-invalid {
5861
@include _mat-select-inner-content-theme($warn);
5962
}
6063
}

src/lib/select/select.spec.ts

Lines changed: 106 additions & 7 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,27 @@ 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+
NgForm,
19+
Validators,
20+
} from '@angular/forms';
21+
import {By} from '@angular/platform-browser';
1222
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
23+
import {TestBed, async, ComponentFixture, fakeAsync, tick, inject} from '@angular/core/testing';
1324
import {MdSelectModule} from './index';
1425
import {OverlayContainer} from '../core/overlay/overlay-container';
1526
import {MdSelect, MdSelectFloatPlaceholderType} from './select';
1627
import {getMdSelectDynamicMultipleError, getMdSelectNonArrayValueError} from './select-errors';
1728
import {MdOption} from '../core/option/option';
1829
import {Dir} from '../core/rtl/dir';
1930
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';
2331
import {Subject} from 'rxjs/Subject';
2432
import {ViewportRuler} from '../core/overlay/position/viewport-ruler';
2533
import {dispatchFakeEvent, dispatchKeyboardEvent} from '../core/testing/dispatch-events';
@@ -55,7 +63,8 @@ describe('MdSelect', () => {
5563
SelectEarlyAccessSibling,
5664
BasicSelectInitiallyHidden,
5765
BasicSelectNoPlaceholder,
58-
BasicSelectWithTheming
66+
BasicSelectWithTheming,
67+
SelectInsideFormGroup
5968
],
6069
providers: [
6170
{provide: OverlayContainer, useFactory: () => {
@@ -1341,11 +1350,12 @@ describe('MdSelect', () => {
13411350
.toEqual('true', `Expected aria-required attr to be true for required selects.`);
13421351
});
13431352

1344-
it('should set aria-invalid for selects that are invalid', () => {
1353+
it('should set aria-invalid for selects that are invalid and touched', () => {
13451354
expect(select.getAttribute('aria-invalid'))
13461355
.toEqual('false', `Expected aria-invalid attr to be false for valid selects.`);
13471356

13481357
fixture.componentInstance.isRequired = true;
1358+
fixture.componentInstance.control.markAsTouched();
13491359
fixture.detectChanges();
13501360

13511361
expect(select.getAttribute('aria-invalid'))
@@ -2022,6 +2032,77 @@ describe('MdSelect', () => {
20222032

20232033
});
20242034

2035+
describe('error state', () => {
2036+
let fixture: ComponentFixture<SelectInsideFormGroup>;
2037+
let testComponent: SelectInsideFormGroup;
2038+
let select: HTMLElement;
2039+
2040+
beforeEach(() => {
2041+
fixture = TestBed.createComponent(SelectInsideFormGroup);
2042+
fixture.detectChanges();
2043+
testComponent = fixture.componentInstance;
2044+
select = fixture.debugElement.query(By.css('md-select')).nativeElement;
2045+
});
2046+
2047+
it('should not set the invalid class on a clean select', () => {
2048+
expect(testComponent.formGroup.untouched).toBe(true, 'Expected the form to be untouched.');
2049+
expect(testComponent.formControl.invalid).toBe(true, 'Expected form control to be invalid.');
2050+
expect(select.classList)
2051+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2052+
expect(select.getAttribute('aria-invalid'))
2053+
.toBe('false', 'Expected aria-invalid to be set to false.');
2054+
});
2055+
2056+
it('should appear as invalid if it becomes touched', () => {
2057+
expect(select.classList)
2058+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2059+
expect(select.getAttribute('aria-invalid'))
2060+
.toBe('false', 'Expected aria-invalid to be set to false.');
2061+
2062+
testComponent.formControl.markAsTouched();
2063+
fixture.detectChanges();
2064+
2065+
expect(select.classList)
2066+
.toContain('mat-select-invalid', 'Expected select to appear invalid.');
2067+
expect(select.getAttribute('aria-invalid'))
2068+
.toBe('true', 'Expected aria-invalid to be set to true.');
2069+
});
2070+
2071+
it('should not have the invalid class when the select becomes valid', () => {
2072+
testComponent.formControl.markAsTouched();
2073+
fixture.detectChanges();
2074+
2075+
expect(select.classList)
2076+
.toContain('mat-select-invalid', 'Expected select to appear invalid.');
2077+
expect(select.getAttribute('aria-invalid'))
2078+
.toBe('true', 'Expected aria-invalid to be set to true.');
2079+
2080+
testComponent.formControl.setValue('pizza-1');
2081+
fixture.detectChanges();
2082+
2083+
expect(select.classList)
2084+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2085+
expect(select.getAttribute('aria-invalid'))
2086+
.toBe('false', 'Expected aria-invalid to be set to false.');
2087+
});
2088+
2089+
it('should appear as invalid when the parent form group is submitted', () => {
2090+
expect(select.classList)
2091+
.not.toContain('mat-select-invalid', 'Expected select not to appear invalid.');
2092+
expect(select.getAttribute('aria-invalid'))
2093+
.toBe('false', 'Expected aria-invalid to be set to false.');
2094+
2095+
dispatchFakeEvent(fixture.debugElement.query(By.css('form')).nativeElement, 'submit');
2096+
fixture.detectChanges();
2097+
2098+
expect(select.classList)
2099+
.toContain('mat-select-invalid', 'Expected select to appear invalid.');
2100+
expect(select.getAttribute('aria-invalid'))
2101+
.toBe('true', 'Expected aria-invalid to be set to true.');
2102+
});
2103+
2104+
});
2105+
20252106
});
20262107

20272108

@@ -2366,3 +2447,21 @@ class BasicSelectWithTheming {
23662447
@ViewChild(MdSelect) select: MdSelect;
23672448
theme: string;
23682449
}
2450+
2451+
@Component({
2452+
template: `
2453+
<form [formGroup]="formGroup">
2454+
<md-select placeholder="Food" formControlName="food">
2455+
<md-option value="steak-0">Steak</md-option>
2456+
<md-option value="pizza-1">Pizza</md-option>
2457+
</md-select>
2458+
</form>
2459+
`
2460+
})
2461+
class SelectInsideFormGroup {
2462+
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
2463+
formControl = new FormControl('', Validators.required);
2464+
formGroup = new FormGroup({
2465+
food: this.formControl
2466+
});
2467+
}

src/lib/select/select.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
Attribute,
1818
OnInit,
1919
} from '@angular/core';
20+
import {NgForm, FormGroupDirective} from '@angular/forms';
2021
import {MdOption, MdOptionSelectionChange} from '../core/option/option';
2122
import {ENTER, SPACE, UP_ARROW, DOWN_ARROW, HOME, END} from '../core/keyboard/keycodes';
2223
import {FocusKeyManager} from '../core/a11y/focus-key-manager';
@@ -108,9 +109,10 @@ export type MdSelectFloatPlaceholderType = 'always' | 'never' | 'auto';
108109
'[attr.aria-labelledby]': 'ariaLabelledby',
109110
'[attr.aria-required]': 'required.toString()',
110111
'[attr.aria-disabled]': 'disabled.toString()',
111-
'[attr.aria-invalid]': '_control?.invalid || "false"',
112+
'[attr.aria-invalid]': '_isErrorState()',
112113
'[attr.aria-owns]': '_optionIds',
113114
'[class.mat-select-disabled]': 'disabled',
115+
'[class.mat-select-invalid]': '_isErrorState()',
114116
'[class.mat-select]': 'true',
115117
'(keydown)': '_handleClosedKeydown($event)',
116118
'(blur)': '_onBlur()',
@@ -313,7 +315,8 @@ export class MdSelect implements AfterContentInit, OnDestroy, OnInit, ControlVal
313315
constructor(private _element: ElementRef, private _renderer: Renderer2,
314316
private _viewportRuler: ViewportRuler, private _changeDetectorRef: ChangeDetectorRef,
315317
@Optional() private _dir: Dir, @Self() @Optional() public _control: NgControl,
316-
@Attribute('tabindex') tabIndex: string) {
318+
@Attribute('tabindex') tabIndex: string, @Optional() private _parentForm: NgForm,
319+
@Optional() private _parentFormGroup: FormGroupDirective) {
317320

318321
if (this._control) {
319322
this._control.valueAccessor = this;
@@ -533,6 +536,16 @@ export class MdSelect implements AfterContentInit, OnDestroy, OnInit, ControlVal
533536
this._setScrollTop();
534537
}
535538

539+
/** Whether the select is in an error state. */
540+
_isErrorState(): boolean {
541+
const isInvalid = this._control && this._control.invalid;
542+
const isTouched = this._control && this._control.touched;
543+
const isSubmitted = (this._parentFormGroup && this._parentFormGroup.submitted) ||
544+
(this._parentForm && this._parentForm.submitted);
545+
546+
return !!(isInvalid && (isTouched || isSubmitted));
547+
}
548+
536549
/**
537550
* Sets the scroll position of the scroll container. This must be called after
538551
* the overlay pane is attached or the scroll container element will not yet be

0 commit comments

Comments
 (0)