Skip to content

Commit

Permalink
fix(material/chips): error if selected value is accessed too early (#…
Browse files Browse the repository at this point in the history
…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)
  • Loading branch information
crisbeto authored and zarend committed Sep 7, 2021
1 parent 2a68fa8 commit eeac3e6
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
17 changes: 16 additions & 1 deletion src/material/chips/chip-list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1380,7 +1380,7 @@ describe('MatChipList', () => {
});
});

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

it('should not throw when accessing the selected value too early in single selection mode',
fakeAsync(() => {
fixture = createComponent(StandardChipList);
const chipList = fixture.debugElement.query(By.directive(MatChipList)).componentInstance;
expect(() => chipList.selected).not.toThrow();
}));

it('should not throw when accessing the selected value too early in multi selection mode',
fakeAsync(() => {
fixture = createComponent(StandardChipList);
const chipList = fixture.debugElement.query(By.directive(MatChipList)).componentInstance;
chipList.multiple = true;
expect(() => chipList.selected).not.toThrow();
}));

function createComponent<T>(component: Type<T>, providers: Provider[] = [], animationsModule:
Type<NoopAnimationsModule> | Type<BrowserAnimationsModule> = NoopAnimationsModule):
ComponentFixture<T> {
Expand Down
3 changes: 2 additions & 1 deletion src/material/chips/chip-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,8 @@ export class MatChipList extends _MatChipListBase implements MatFormFieldControl

/** The array of selected chips inside chip list. */
get selected(): MatChip[] | MatChip {
return this.multiple ? this._selectionModel.selected : this._selectionModel.selected[0];
return this.multiple ? (this._selectionModel?.selected || []) :
this._selectionModel?.selected[0];
}

/** The ARIA role applied to the chip list. */
Expand Down

0 comments on commit eeac3e6

Please sign in to comment.