Skip to content

Commit 458256d

Browse files
committed
fix(autocomplete): error if panel is added asynchronously
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 53c42a4 commit 458256d

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
@@ -387,7 +387,9 @@ export class MatAutocompleteTrigger implements ControlValueAccessor, OnDestroy {
387387
}
388388

389389
private _setTriggerValue(value: any): void {
390-
const toDisplay = this.autocomplete.displayWith ? this.autocomplete.displayWith(value) : value;
390+
const toDisplay = this.autocomplete && this.autocomplete.displayWith ?
391+
this.autocomplete.displayWith(value) :
392+
value;
391393

392394
// Simply falling back to an empty string if the display value is falsy does not work properly.
393395
// 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
@@ -1467,6 +1467,15 @@ describe('MatAutocomplete', () => {
14671467
}).toThrow(getMatAutocompleteMissingPanelError());
14681468
}));
14691469

1470+
it('should not throw on init, even if the panel is not defined', fakeAsync(() => {
1471+
expect(() => {
1472+
const fixture = TestBed.createComponent(AutocompleteWithoutPanel);
1473+
fixture.componentInstance.control.setValue('Something');
1474+
fixture.detectChanges();
1475+
tick();
1476+
}).not.toThrow();
1477+
}));
1478+
14701479
it('should hide the placeholder with a preselected form control value ' +
14711480
'and a disabled floating placeholder', fakeAsync(() => {
14721481
const fixture = TestBed.createComponent(AutocompleteWithFormsAndNonfloatingPlaceholder);
@@ -1821,10 +1830,11 @@ class AutocompleteWithNativeInput {
18211830

18221831

18231832
@Component({
1824-
template: `<input placeholder="Choose" [matAutocomplete]="auto">`
1833+
template: `<input placeholder="Choose" [matAutocomplete]="auto" [formControl]="control">`
18251834
})
18261835
class AutocompleteWithoutPanel {
18271836
@ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger;
1837+
control = new FormControl();
18281838
}
18291839

18301840

0 commit comments

Comments
 (0)