Skip to content

Commit

Permalink
fix(selection-list): remove selected option from model value on destr…
Browse files Browse the repository at this point in the history
…oy (angular#9106)

Fixes selected options that are removed from the DOM not being removed from the model.

Relates to angular#9104.
  • Loading branch information
crisbeto authored and jelbourn committed Jan 8, 2018
1 parent dfb5655 commit b4fe8b3
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
19 changes: 18 additions & 1 deletion src/lib/list/selection-list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -869,11 +885,12 @@ class SelectionListWithTabindexBinding {
<mat-selection-list [(ngModel)]="selectedOptions">
<mat-list-option value="opt1">Option 1</mat-list-option>
<mat-list-option value="opt2">Option 2</mat-list-option>
<mat-list-option value="opt3">Option 3</mat-list-option>
<mat-list-option value="opt3" *ngIf="renderLastOption">Option 3</mat-list-option>
</mat-selection-list>`
})
class SelectionListWithModel {
selectedOptions: string[] = [];
renderLastOption = true;
}

@Component({
Expand Down
6 changes: 6 additions & 0 deletions src/lib/list/selection-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down

0 comments on commit b4fe8b3

Please sign in to comment.