From 81f8fb95821d930ea518441aa372d42ace333fce Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Wed, 7 Nov 2018 18:20:26 +0000 Subject: [PATCH] fix(button-toggle): not forwarding focus to underlying control (#14001) Fixes the button toggle host element not being able to receive focus which means that it can't be used with the focus trap directives. Also fixes that when it does receive focus, it won't forward it to the underlying `button` element. --- src/lib/button-toggle/button-toggle.spec.ts | 16 +++++++++++++++- src/lib/button-toggle/button-toggle.ts | 6 ++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/lib/button-toggle/button-toggle.spec.ts b/src/lib/button-toggle/button-toggle.spec.ts index 2cbca33c716..9a98d523802 100644 --- a/src/lib/button-toggle/button-toggle.spec.ts +++ b/src/lib/button-toggle/button-toggle.spec.ts @@ -723,7 +723,21 @@ describe('MatButtonToggle without forms', () => { const host = fixture.nativeElement.querySelector('.mat-button-toggle'); - expect(host.hasAttribute('tabindex')).toBe(false); + expect(host.getAttribute('tabindex')).toBe('-1'); + }); + + it('should forward focus to the underlying button when the host is focused', () => { + const fixture = TestBed.createComponent(ButtonToggleWithTabindex); + fixture.detectChanges(); + + const host = fixture.nativeElement.querySelector('.mat-button-toggle'); + const button = host.querySelector('button'); + + expect(document.activeElement).not.toBe(button); + + host.focus(); + + expect(document.activeElement).toBe(button); }); }); diff --git a/src/lib/button-toggle/button-toggle.ts b/src/lib/button-toggle/button-toggle.ts index e827ab30319..c4b728bc9da 100644 --- a/src/lib/button-toggle/button-toggle.ts +++ b/src/lib/button-toggle/button-toggle.ts @@ -365,9 +365,11 @@ export const _MatButtonToggleMixinBase: CanDisableRippleCtor & typeof MatButtonT '[class.mat-button-toggle-disabled]': 'disabled', '[class.mat-button-toggle-appearance-standard]': 'appearance === "standard"', 'class': 'mat-button-toggle', - // Clear out the native tabindex here since we forward it to the underlying button - '[attr.tabindex]': 'null', + // Always reset the tabindex to -1 so it doesn't conflict with the one on the `button`, + // but can still receive focus from things like cdkFocusInitial. + '[attr.tabindex]': '-1', '[attr.id]': 'id', + '(focus)': 'focus()', } }) export class MatButtonToggle extends _MatButtonToggleMixinBase implements OnInit,