From 51ddecbbbd669c29fbe2cd99f55ad3a3ba716b4b Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Mon, 21 Mar 2022 14:33:21 +0100 Subject: [PATCH] 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. (cherry picked from commit 93716067541daf3a0a47c137f6b287f47a347e2e) --- src/material/checkbox/checkbox.spec.ts | 15 +++++++++++++-- src/material/checkbox/checkbox.ts | 3 ++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/material/checkbox/checkbox.spec.ts b/src/material/checkbox/checkbox.spec.ts index 4ce92570338d..4e2db7b7b03b 100644 --- a/src/material/checkbox/checkbox.spec.ts +++ b/src/material/checkbox/checkbox.spec.ts @@ -950,7 +950,7 @@ describe('MatCheckbox', () => { let inputElement: HTMLInputElement; let ngModel: NgModel; - beforeEach(() => { + beforeEach(fakeAsync(() => { fixture = createComponent(CheckboxWithNgModel); fixture.componentInstance.isRequired = false; @@ -961,7 +961,7 @@ describe('MatCheckbox', () => { checkboxInstance = checkboxDebugElement.componentInstance; inputElement = checkboxNativeElement.querySelector('input'); ngModel = checkboxDebugElement.injector.get(NgModel); - }); + })); it('should be pristine, untouched, and valid initially', () => { expect(ngModel.valid).toBe(true); @@ -1059,6 +1059,17 @@ describe('MatCheckbox', () => { expect(checkboxInstance.checked).toBe(false); expect(ngModel.valid).toBe(false); }); + + it('should update the ngModel value when using the `toggle` method', fakeAsync(() => { + const checkbox = fixture.debugElement.query(By.directive(MatCheckbox)).componentInstance; + + expect(fixture.componentInstance.isGood).toBe(false); + + checkbox.toggle(); + fixture.detectChanges(); + + expect(fixture.componentInstance.isGood).toBe(true); + })); }); describe('with name attribute', () => { diff --git a/src/material/checkbox/checkbox.ts b/src/material/checkbox/checkbox.ts index 1277429d604c..f9a7d5031848 100644 --- a/src/material/checkbox/checkbox.ts +++ b/src/material/checkbox/checkbox.ts @@ -406,6 +406,7 @@ export class MatCheckbox /** Toggles the `checked` state of the checkbox. */ toggle(): void { this.checked = !this.checked; + this._controlValueAccessorChangeFn(this.checked); } /** @@ -437,7 +438,7 @@ export class MatCheckbox }); } - this.toggle(); + this._checked = !this._checked; this._transitionCheckState( this._checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked, );