From fa29a7d4d88fe342b1571b00247698dd8739a1c3 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Fri, 5 Jan 2018 00:03:26 +0200 Subject: [PATCH] fix(selection-list): remove selected option from model value on destroy (#9106) Fixes selected options that are removed from the DOM not being removed from the model. Relates to #9104. --- src/lib/list/selection-list.spec.ts | 19 ++++++++++++++++++- src/lib/list/selection-list.ts | 6 ++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/src/lib/list/selection-list.spec.ts b/src/lib/list/selection-list.spec.ts index b31c1ed5ec2c..876309677edb 100644 --- a/src/lib/list/selection-list.spec.ts +++ b/src/lib/list/selection-list.spec.ts @@ -675,6 +675,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', () => { @@ -869,11 +885,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 0e9ce47bd3df..bcd8cfa7767a 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); }