Skip to content

Commit

Permalink
fix(material/checkbox): model value not updated when using toggle met…
Browse files Browse the repository at this point in the history
…hod (#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 9371606)
  • Loading branch information
crisbeto committed Mar 21, 2022
1 parent 43fcdde commit 51ddecb
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
15 changes: 13 additions & 2 deletions src/material/checkbox/checkbox.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -950,7 +950,7 @@ describe('MatCheckbox', () => {
let inputElement: HTMLInputElement;
let ngModel: NgModel;

beforeEach(() => {
beforeEach(fakeAsync(() => {
fixture = createComponent(CheckboxWithNgModel);

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

it('should be pristine, untouched, and valid initially', () => {
expect(ngModel.valid).toBe(true);
Expand Down Expand Up @@ -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', () => {
Expand Down
3 changes: 2 additions & 1 deletion src/material/checkbox/checkbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,7 @@ export class MatCheckbox
/** Toggles the `checked` state of the checkbox. */
toggle(): void {
this.checked = !this.checked;
this._controlValueAccessorChangeFn(this.checked);
}

/**
Expand Down Expand Up @@ -437,7 +438,7 @@ export class MatCheckbox
});
}

this.toggle();
this._checked = !this._checked;
this._transitionCheckState(
this._checked ? TransitionCheckState.Checked : TransitionCheckState.Unchecked,
);
Expand Down

0 comments on commit 51ddecb

Please sign in to comment.