diff --git a/src/lib/list/selection-list.spec.ts b/src/lib/list/selection-list.spec.ts index 14614bad7915..6a38438eba4d 100644 --- a/src/lib/list/selection-list.spec.ts +++ b/src/lib/list/selection-list.spec.ts @@ -659,6 +659,22 @@ describe('MatSelectionList with forms', () => { expect(ngModel.pristine) .toBe(false, 'Expected the selection-list to be dirty after state change.'); })); + + it('should remove a selected option from the value on destroy', fakeAsync(() => { + listOptions[1].selected = true; + listOptions[2].selected = true; + + fixture.detectChanges(); + + expect(fixture.componentInstance.selectedOptions).toEqual(['opt2', 'opt3']); + + fixture.componentInstance.renderLastOption = false; + fixture.detectChanges(); + tick(); + + expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']); + })); + }); describe('and formControl', () => { @@ -853,11 +869,12 @@ class SelectionListWithTabindexBinding { Option 1 Option 2 - Option 3 + Option 3 ` }) class SelectionListWithModel { selectedOptions: string[] = []; + renderLastOption = true; } @Component({ diff --git a/src/lib/list/selection-list.ts b/src/lib/list/selection-list.ts index 596a4add6df8..29888fcc9a35 100644 --- a/src/lib/list/selection-list.ts +++ b/src/lib/list/selection-list.ts @@ -178,6 +178,12 @@ export class MatListOption extends _MatListOptionMixinBase } ngOnDestroy(): void { + if (this.selected) { + // We have to delay this until the next tick in order + // to avoid changed after checked errors. + Promise.resolve().then(() => this.selected = false); + } + this.selectionList._removeOptionFromList(this); }