From 5575673b4acb094f0aabc0830cfcffc5151ad739 Mon Sep 17 00:00:00 2001 From: Jessica Xu Date: Mon, 2 Nov 2020 22:11:09 -0800 Subject: [PATCH] feat(material/checkbox): allow focus origin to be optional input in focus method (#20905) Co-authored-by: Jessica Xu --- src/material/checkbox/checkbox.spec.ts | 15 +++++++++++++++ src/material/checkbox/checkbox.ts | 8 ++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/material/checkbox/checkbox.spec.ts b/src/material/checkbox/checkbox.spec.ts index 49eb7ece9b17..930f3b296ce1 100644 --- a/src/material/checkbox/checkbox.spec.ts +++ b/src/material/checkbox/checkbox.spec.ts @@ -909,6 +909,21 @@ describe('MatCheckbox', () => { expect(secondId).toMatch(/mat-checkbox-\d+-input/); expect(firstId).not.toEqual(secondId); }); + + it('should not change focus origin if origin not specified', () => { + let [firstCheckboxDebugEl, secondCheckboxDebugEl] = + fixture.debugElement.queryAll(By.directive(MatCheckbox)); + fixture.detectChanges(); + + const firstCheckboxInstance = firstCheckboxDebugEl.componentInstance as MatCheckbox; + const secondCheckboxInstance = secondCheckboxDebugEl.componentInstance as MatCheckbox; + + firstCheckboxInstance.focus('mouse'); + secondCheckboxInstance.focus(); + + expect(secondCheckboxDebugEl.nativeElement.classList).toContain('cdk-focused'); + expect(secondCheckboxDebugEl.nativeElement.classList).toContain('cdk-mouse-focused'); + }); }); describe('with ngModel', () => { diff --git a/src/material/checkbox/checkbox.ts b/src/material/checkbox/checkbox.ts index d4a417914e6a..775e9ab8d5ab 100644 --- a/src/material/checkbox/checkbox.ts +++ b/src/material/checkbox/checkbox.ts @@ -425,8 +425,12 @@ export class MatCheckbox extends _MatCheckboxMixinBase implements ControlValueAc } /** Focuses the checkbox. */ - focus(origin: FocusOrigin = 'keyboard', options?: FocusOptions): void { - this._focusMonitor.focusVia(this._inputElement, origin, options); + focus(origin?: FocusOrigin, options?: FocusOptions): void { + if (origin) { + this._focusMonitor.focusVia(this._inputElement, origin, options); + } else { + this._inputElement.nativeElement.focus(options); + } } _onInteractionEvent(event: Event) {