Skip to content

Commit 9371606

Browse files
authored
fix(material/checkbox): model value not updated when using toggle method (#11902)
Along the same lines as #11812. The checkbox doesn't update its `ControlValueAccessor` value when it is toggled via the `toggle` method.
1 parent bf4ba23 commit 9371606

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

src/material/checkbox/checkbox.spec.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -950,7 +950,7 @@ describe('MatCheckbox', () => {
950950
let inputElement: HTMLInputElement;
951951
let ngModel: NgModel;
952952

953-
beforeEach(() => {
953+
beforeEach(fakeAsync(() => {
954954
fixture = createComponent(CheckboxWithNgModel);
955955

956956
fixture.componentInstance.isRequired = false;
@@ -961,7 +961,7 @@ describe('MatCheckbox', () => {
961961
checkboxInstance = checkboxDebugElement.componentInstance;
962962
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input');
963963
ngModel = checkboxDebugElement.injector.get<NgModel>(NgModel);
964-
});
964+
}));
965965

966966
it('should be pristine, untouched, and valid initially', () => {
967967
expect(ngModel.valid).toBe(true);
@@ -1059,6 +1059,17 @@ describe('MatCheckbox', () => {
10591059
expect(checkboxInstance.checked).toBe(false);
10601060
expect(ngModel.valid).toBe(false);
10611061
});
1062+
1063+
it('should update the ngModel value when using the `toggle` method', fakeAsync(() => {
1064+
const checkbox = fixture.debugElement.query(By.directive(MatCheckbox)).componentInstance;
1065+
1066+
expect(fixture.componentInstance.isGood).toBe(false);
1067+
1068+
checkbox.toggle();
1069+
fixture.detectChanges();
1070+
1071+
expect(fixture.componentInstance.isGood).toBe(true);
1072+
}));
10621073
});
10631074

10641075
describe('with name attribute', () => {

src/material/checkbox/checkbox.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,7 @@ export class MatCheckbox
406406
/** Toggles the `checked` state of the checkbox. */
407407
toggle(): void {
408408
this.checked = !this.checked;
409+
this._controlValueAccessorChangeFn(this.checked);
409410
}
410411

411412
/**
@@ -437,7 +438,7 @@ export class MatCheckbox
437438
});
438439
}
439440

440-
this.toggle();
441+
this._checked = !this._checked;
441442
this._transitionCheckState(
442443
this._checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked,
443444
);

0 commit comments

Comments
 (0)