Skip to content

Commit 875f00d

Browse files
authored
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.
1 parent c717ea4 commit 875f00d

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
@@ -1387,7 +1387,7 @@ describe('MatChipList', () => {
13871387
});
13881388
});
13891389

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

1400+
it('should not throw when accessing the selected value too early in single selection mode',
1401+
fakeAsync(() => {
1402+
fixture = createComponent(StandardChipList);
1403+
const chipList = fixture.debugElement.query(By.directive(MatChipList)).componentInstance;
1404+
expect(() => chipList.selected).not.toThrow();
1405+
}));
1406+
1407+
it('should not throw when accessing the selected value too early in multi selection mode',
1408+
fakeAsync(() => {
1409+
fixture = createComponent(StandardChipList);
1410+
const chipList = fixture.debugElement.query(By.directive(MatChipList)).componentInstance;
1411+
chipList.multiple = true;
1412+
expect(() => chipList.selected).not.toThrow();
1413+
}));
1414+
14001415
function createComponent<T>(component: Type<T>, providers: Provider[] = [], animationsModule:
14011416
Type<NoopAnimationsModule> | Type<BrowserAnimationsModule> = NoopAnimationsModule):
14021417
ComponentFixture<T> {

src/material/chips/chip-list.ts

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

161161
/** The array of selected chips inside chip list. */
162162
get selected(): MatChip[] | MatChip {
163-
return this.multiple ? this._selectionModel.selected : this._selectionModel.selected[0];
163+
return this.multiple ? (this._selectionModel?.selected || []) :
164+
this._selectionModel?.selected[0];
164165
}
165166

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

0 commit comments

Comments
 (0)