Skip to content

Commit 02a1334

Browse files
crisbetojelbourn
authored andcommitted
fix(selection-list): remove selected option from model value on destroy (angular#9106)
Fixes selected options that are removed from the DOM not being removed from the model. Relates to angular#9104.
1 parent 2235239 commit 02a1334

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,22 @@ describe('MatSelectionList with forms', () => {
659659
expect(ngModel.pristine)
660660
.toBe(false, 'Expected the selection-list to be dirty after state change.');
661661
}));
662+
663+
it('should remove a selected option from the value on destroy', fakeAsync(() => {
664+
listOptions[1].selected = true;
665+
listOptions[2].selected = true;
666+
667+
fixture.detectChanges();
668+
669+
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2', 'opt3']);
670+
671+
fixture.componentInstance.renderLastOption = false;
672+
fixture.detectChanges();
673+
tick();
674+
675+
expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']);
676+
}));
677+
662678
});
663679

664680
describe('and formControl', () => {
@@ -853,11 +869,12 @@ class SelectionListWithTabindexBinding {
853869
<mat-selection-list [(ngModel)]="selectedOptions">
854870
<mat-list-option value="opt1">Option 1</mat-list-option>
855871
<mat-list-option value="opt2">Option 2</mat-list-option>
856-
<mat-list-option value="opt3">Option 3</mat-list-option>
872+
<mat-list-option value="opt3" *ngIf="renderLastOption">Option 3</mat-list-option>
857873
</mat-selection-list>`
858874
})
859875
class SelectionListWithModel {
860876
selectedOptions: string[] = [];
877+
renderLastOption = true;
861878
}
862879

863880
@Component({

src/lib/list/selection-list.ts

Lines changed: 6 additions & 0 deletions
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)