Skip to content

Commit 504ba70

Browse files
crisbetoandrewseguin
authored andcommitted
fix(autocomplete): error if panel is added asynchronously (#7078)
Fixes an error that was thrown when an autocomplete trigger is initialized without a panel. Note that an error will still be thrown, but only if the user attempts to open the panel. Fixes #7069.
1 parent 8e77261 commit 504ba70

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

src/lib/autocomplete/autocomplete-trigger.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,9 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
390390
}
391391

392392
private _setTriggerValue(value: any): void {
393-
const toDisplay = this.autocomplete.displayWith ? this.autocomplete.displayWith(value) : value;
393+
const toDisplay = this.autocomplete && this.autocomplete.displayWith ?
394+
this.autocomplete.displayWith(value) :
395+
value;
394396

395397
// Simply falling back to an empty string if the display value is falsy does not work properly.
396398
// The display value can also be the number zero and shouldn't fall back to an empty string.

src/lib/autocomplete/autocomplete.spec.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1512,6 +1512,15 @@ describe('MatAutocomplete', () => {
15121512
}).toThrow(getMatAutocompleteMissingPanelError());
15131513
}));
15141514

1515+
it('should not throw on init, even if the panel is not defined', fakeAsync(() => {
1516+
expect(() => {
1517+
const fixture = TestBed.createComponent(AutocompleteWithoutPanel);
1518+
fixture.componentInstance.control.setValue('Something');
1519+
fixture.detectChanges();
1520+
tick();
1521+
}).not.toThrow();
1522+
}));
1523+
15151524
it('should hide the placeholder with a preselected form control value ' +
15161525
'and a disabled floating placeholder', fakeAsync(() => {
15171526
const fixture = TestBed.createComponent(AutocompleteWithFormsAndNonfloatingPlaceholder);
@@ -1885,10 +1894,11 @@ class AutocompleteWithNativeInput {
18851894

18861895

18871896
@Component({
1888-
template: `<input placeholder="Choose" [matAutocomplete]="auto">`
1897+
template: `<input placeholder="Choose" [matAutocomplete]="auto" [formControl]="control">`
18891898
})
18901899
class AutocompleteWithoutPanel {
18911900
@ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
1901+
control = new FormControl();
18921902
}
18931903

18941904

0 commit comments

Comments
 (0)