Skip to content

Commit 4fdb546

Browse files
committed
fix(selection-list): remove selected option from model value on destroy
Fixes selected options that are removed from the DOM not being removed from the model. Relates to #9104.
1 parent 5414480 commit 4fdb546

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/lib/list/selection-list.spec.ts

+18-1
Original file line numberDiff line numberDiff line change
@@ -650,6 +650,22 @@ describe('MatSelectionList with forms', () => {
650650
expect(ngModel.pristine)
651651
.toBe(false, 'Expected the selection-list to be dirty after state change.');
652652
}));
653+
654+
it('should remove a selected option from the value on destroy', fakeAsync(() => {
655+
listOptions[1].selected = true;
656+
listOptions[2].selected = true;
657+
658+
fixture.detectChanges();
659+
660+
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2', 'opt3']);
661+
662+
fixture.componentInstance.renderLastOption = false;
663+
fixture.detectChanges();
664+
tick();
665+
666+
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']);
667+
}));
668+
653669
});
654670

655671
describe('and formControl', () => {
@@ -800,11 +816,12 @@ class SelectionListWithTabindexBinding {
800816
<mat-selection-list [(ngModel)]="selectedOptions">
801817
<mat-list-option value="opt1">Option 1</mat-list-option>
802818
<mat-list-option value="opt2">Option 2</mat-list-option>
803-
<mat-list-option value="opt3">Option 3</mat-list-option>
819+
<mat-list-option value="opt3" *ngIf="renderLastOption">Option 3</mat-list-option>
804820
</mat-selection-list>`
805821
})
806822
class SelectionListWithModel {
807823
selectedOptions: string[] = [];
824+
renderLastOption = true;
808825
}
809826

810827
@Component({

src/lib/list/selection-list.ts

+6
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,12 @@ export class MatListOption extends _MatListOptionMixinBase
178178
}
179179

180180
ngOnDestroy(): void {
181+
if (this.selected) {
182+
// We have to delay this until the next tick in order
183+
// to avoid changed after checked errors.
184+
Promise.resolve().then(() => this.selected = false);
185+
}
186+
181187
this.selectionList._removeOptionFromList(this);
182188
}
183189

0 commit comments

Comments
 (0)