Skip to content

fix(material/chips): error if selected value is accessed too early #23419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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