Skip to content

Commit

Permalink
fix(autocomplete): make writeValue method synchronous
Browse files Browse the repository at this point in the history
Refactors the `MatAutocompleteTrigger.writeValue` method to avoid having to use a `Promise.resolve` to defer rendering. This makes it easier to test and avoids potential race conditions. It seems like the reason it was added in the first place was to be able to handle components that have a preselected value through a `FormControl` as well as a custom `displayWith` function.

Fixes angular#3250.
  • Loading branch information
crisbeto committed Aug 24, 2018
1 parent 29d5173 commit 28171de
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/lib/autocomplete/autocomplete-trigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {TemplatePortal} from '@angular/cdk/portal';
import {DOCUMENT} from '@angular/common';
import {filter, take, switchMap, delay, tap, map} from 'rxjs/operators';
import {
AfterContentChecked,
ChangeDetectorRef,
Directive,
ElementRef,
Expand Down Expand Up @@ -115,7 +116,8 @@ export function getMatAutocompleteMissingPanelError(): Error {
exportAs: 'matAutocompleteTrigger',
providers: [MAT_AUTOCOMPLETE_VALUE_ACCESSOR]
})
export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
export class MatAutocompleteTrigger implements ControlValueAccessor, AfterContentChecked,
OnDestroy {
private _overlayRef: OverlayRef | null;
private _portal: TemplatePortal;
private _componentDestroyed = false;
Expand Down Expand Up @@ -143,6 +145,12 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
*/
private _canOpenOnNextFocus = true;

/** Whether the component has been initializied. */
private _isInitialized: boolean;

/** Initial value that should be shown after the component is initialized. */
private _initialValueToSelect: any;

/** Stream of keyboard events that can close the panel. */
private readonly _closeKeyEventStream = new Subject<void>();

Expand Down Expand Up @@ -207,6 +215,15 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
}
}

ngAfterContentChecked() {
if (!this._isInitialized && typeof this._initialValueToSelect !== 'undefined') {
this._setTriggerValue(this._initialValueToSelect);
this._initialValueToSelect = undefined;
}

this._isInitialized = true;
}

ngOnDestroy() {
if (typeof window !== 'undefined') {
window.removeEventListener('blur', this._windowBlurHandler);
Expand Down Expand Up @@ -336,7 +353,14 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {

// Implemented as part of ControlValueAccessor.
writeValue(value: any): void {
Promise.resolve(null).then(() => this._setTriggerValue(value));
if (this._isInitialized) {
this._setTriggerValue(value);
} else {
// If the component isn't initialized yet, defer until the first CD pass, otherwise we'll
// miss the initial `displayWith` value. By deferring until the first `AfterContentChecked`
// we avoid making the method async while preventing "changed after checked" errors.
this._initialValueToSelect = value;
}
}

// Implemented as part of ControlValueAccessor.
Expand Down
37 changes: 37 additions & 0 deletions src/lib/autocomplete/autocomplete.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2199,6 +2199,17 @@ describe('MatAutocomplete', () => {
expect(Math.floor(overlayRect.top)).toBe(Math.floor(originRect.bottom),
'Expected autocomplete panel to align with the bottom of the new origin.');
});

it('should evaluate `displayWith` before assigning the initial value', fakeAsync(() => {
const fixture = createComponent(PreselectedAutocompleteDisplayWith);
const input = fixture.nativeElement.querySelector('input');

fixture.detectChanges();
flush();

expect(input.value).toBe('Alaska');
}));

});

@Component({
Expand Down Expand Up @@ -2585,3 +2596,29 @@ class AutocompleteWithNativeAutocompleteAttribute {
})
class InputWithoutAutocompleteAndDisabled {
}


@Component({
template: `
<mat-form-field>
<input matInput [matAutocomplete]="auto" [formControl]="stateCtrl">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let state of states" [value]="state">
<span>{{ state.name }}</span>
</mat-option>
</mat-autocomplete>
`
})
class PreselectedAutocompleteDisplayWith {
stateCtrl = new FormControl({code: 'AK', name: 'Alaska'});
states = [
{code: 'AL', name: 'Alabama'},
{code: 'AK', name: 'Alaska'}
];

displayFn(value: any): string {
return value && typeof value === 'object' ? value.name : value;
}
}

0 comments on commit 28171de

Please sign in to comment.