Skip to content

Commit eeac3e6

Browse files
crisbetozarend
authored andcommitted
fix(material/chips): error if selected value is accessed too early (#23419)
Similar issue to #23378. The chip list will throw an error if the `selected` value is accessed before the selection model has been initialized. (cherry picked from commit 875f00d)
1 parent 2a68fa8 commit eeac3e6

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/material/chips/chip-list.spec.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1380,7 +1380,7 @@ describe('MatChipList', () => {
13801380
});
13811381
});
13821382

1383-
it('should preselected chip as selected inside an OnPush component', fakeAsync(() => {
1383+
it('should preselect chip as selected inside an OnPush component', fakeAsync(() => {
13841384
fixture = createComponent(PreselectedChipInsideOnPush);
13851385
fixture.detectChanges();
13861386
tick();
@@ -1390,6 +1390,21 @@ describe('MatChipList', () => {
13901390
.withContext('Expected first chip to be selected.').toContain('mat-chip-selected');
13911391
}));
13921392

1393+
it('should not throw when accessing the selected value too early in single selection mode',
1394+
fakeAsync(() => {
1395+
fixture = createComponent(StandardChipList);
1396+
const chipList = fixture.debugElement.query(By.directive(MatChipList)).componentInstance;
1397+
expect(() => chipList.selected).not.toThrow();
1398+
}));
1399+
1400+
it('should not throw when accessing the selected value too early in multi selection mode',
1401+
fakeAsync(() => {
1402+
fixture = createComponent(StandardChipList);
1403+
const chipList = fixture.debugElement.query(By.directive(MatChipList)).componentInstance;
1404+
chipList.multiple = true;
1405+
expect(() => chipList.selected).not.toThrow();
1406+
}));
1407+
13931408
function createComponent<T>(component: Type<T>, providers: Provider[] = [], animationsModule:
13941409
Type<NoopAnimationsModule> | Type<BrowserAnimationsModule> = NoopAnimationsModule):
13951410
ComponentFixture<T> {

src/material/chips/chip-list.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,8 @@ export class MatChipList extends _MatChipListBase implements MatFormFieldControl
154154

155155
/** The array of selected chips inside chip list. */
156156
get selected(): MatChip[] | MatChip {
157-
return this.multiple ? this._selectionModel.selected : this._selectionModel.selected[0];
157+
return this.multiple ? (this._selectionModel?.selected || []) :
158+
this._selectionModel?.selected[0];
158159
}
159160

160161
/** The ARIA role applied to the chip list. */

0 commit comments

Comments
 (0)