Skip to content

fix(button-toggle): remove references to selected toggle on destroy #14627

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/lib/button-toggle/button-toggle.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -416,6 +416,23 @@ describe('MatButtonToggle without forms', () => {

expect(buttonToggleInstances.every(toggle => !toggle.checked)).toBe(true);
});

it('should update the model if a selected toggle is removed', fakeAsync(() => {
expect(groupInstance.value).toBeFalsy();
buttonToggleLabelElements[0].click();
fixture.detectChanges();

expect(groupInstance.value).toBe('test1');
expect(groupInstance.selected).toBe(buttonToggleInstances[0]);

testComponent.renderFirstToggle = false;
fixture.detectChanges();
tick();

expect(groupInstance.value).toBeFalsy();
expect(groupInstance.selected).toBeFalsy();
}));

});

describe('with initial value and change event', () => {
Expand Down Expand Up @@ -787,7 +804,7 @@ describe('MatButtonToggle without forms', () => {
<mat-button-toggle-group [disabled]="isGroupDisabled"
[vertical]="isVertical"
[(value)]="groupValue">
<mat-button-toggle value="test1">Test1</mat-button-toggle>
<mat-button-toggle value="test1" *ngIf="renderFirstToggle">Test1</mat-button-toggle>
<mat-button-toggle value="test2">Test2</mat-button-toggle>
<mat-button-toggle value="test3">Test3</mat-button-toggle>
</mat-button-toggle-group>
Expand All @@ -797,6 +814,7 @@ class ButtonTogglesInsideButtonToggleGroup {
isGroupDisabled: boolean = false;
isVertical: boolean = false;
groupValue: string;
renderFirstToggle = true;
}

@Component({
Expand Down
8 changes: 8 additions & 0 deletions src/lib/button-toggle/button-toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,15 @@ export class MatButtonToggle extends _MatButtonToggleMixinBase implements OnInit
}

ngOnDestroy() {
const group = this.buttonToggleGroup;

this._focusMonitor.stopMonitoring(this._elementRef);

// Remove the toggle from the selection once it's destroyed. Needs to happen
// on the next tick in order to avoid "changed after checked" errors.
if (group && group._isSelected(this)) {
Promise.resolve().then(() => group._syncButtonToggle(this, false));
}
}

/** Focuses the button. */
Expand Down