From 8a16abf51f7cf5e84d3f72c9e38968a4bb26b5f4 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Thu, 2 Feb 2023 10:40:32 +0100 Subject: [PATCH] fix(material/checkbox): focus not moved to input when clicking on touch target Fixes that while we were toggling the checked state of a checkbox when its touch target is clicked, we weren't moving focus to the internal `input`. Fixes #26486. --- src/material/checkbox/checkbox.html | 2 +- src/material/checkbox/checkbox.spec.ts | 14 ++++++++++++++ src/material/checkbox/checkbox.ts | 10 ++++++++++ tools/public_api_guard/material/checkbox.md | 2 ++ 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/src/material/checkbox/checkbox.html b/src/material/checkbox/checkbox.html index 303eb8fc6ddd..5c9cbab0416e 100644 --- a/src/material/checkbox/checkbox.html +++ b/src/material/checkbox/checkbox.html @@ -3,7 +3,7 @@ (click)="_preventBubblingFromLabel($event)">
-
+
{ expect(document.activeElement).toBe(inputElement); })); + it('should focus underlying input element when the touch target is clicked', fakeAsync(() => { + const touchTarget = checkboxElement.querySelector( + '.mat-mdc-checkbox-touch-target', + ) as HTMLElement; + + expect(document.activeElement).not.toBe(inputElement); + + touchTarget.click(); + fixture.detectChanges(); + flush(); + + expect(document.activeElement).toBe(inputElement); + })); + it('should forward the value to input element', fakeAsync(() => { testComponent.checkboxValue = 'basic_checkbox'; fixture.detectChanges(); diff --git a/src/material/checkbox/checkbox.ts b/src/material/checkbox/checkbox.ts index c32946fd88d1..2f97a74ef393 100644 --- a/src/material/checkbox/checkbox.ts +++ b/src/material/checkbox/checkbox.ts @@ -547,6 +547,16 @@ export class MatCheckbox super._handleInputClick(); } + _onTouchTargetClick() { + super._handleInputClick(); + + if (!this.disabled) { + // Normally the input should be focused already, but if the click + // comes from the touch target, then we might have to focus it ourselves. + this._inputElement.nativeElement.focus(); + } + } + /** * Prevent click events that come from the `