Skip to content

bug(mat-select): accessing selected field on a MatSelect instance causes exception #23371

Closed
@AndrewKushnir

Description

@AndrewKushnir

Reproduction

The following code in a template:

<mat-select
  [matTooltip]="$any(select.selected)?.viewValue"
  #select>
</mat-select>

results in the JS error below:

core.umd.js:6824 ERROR TypeError: Cannot read property 'selected' of undefined
    at MatSelect.get (material-select.umd.js:870)
    at ExampleComponent_Template (VM322 example-component.ts:18)
    at executeTemplate (core.umd.js:10101)
    at refreshView (core.umd.js:9967)
    at refreshComponent (core.umd.js:11140)
    at refreshChildComponents (core.umd.js:9763)
    at refreshView (core.umd.js:10017)
    at renderComponentOrTemplate (core.umd.js:10081)
    at tickRootContext (core.umd.js:11314)
    at detectChangesInRootView (core.umd.js:11339)

Stackblitz repro: https://stackblitz.com/edit/components-issue-8aohka?file=src%2Fapp%2Fexample-component.html

The problem is coming from this code:

get selected(): MatOption | MatOption[] {
return this.multiple ? this._selectionModel.selected : this._selectionModel.selected[0];
}

where the this._selectionModel is undefined when we try to access it. There is an empty function which checks for the `` presence:

get empty(): boolean {
return !this._selectionModel || this._selectionModel.isEmpty();
}

The empty function is used as a guard in some other internal functions in MatSelect, so it can probably be added to the selected getter too. However the signature of the selected getter (MatOption | MatOption[]) doesn't account for the fact that there might be no selected option at all, so this would likely be a breaking change (from types perspective, since it's a public API).

The issue was originally reported internally (internal reference).

Metadata

Metadata

Assignees

Labels

GThis is is related to a Google internal issueP3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: material/select

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions