Skip to content

Commit b7be573

Browse files
crisbetoVivian Hu
authored andcommitted
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.
1 parent 1d4be69 commit b7be573

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/lib/button-toggle/button-toggle.spec.ts

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -723,7 +723,21 @@ describe('MatButtonToggle without forms', () => {
723723

724724
const host = fixture.nativeElement.querySelector('.mat-button-toggle');
725725

726-
expect(host.hasAttribute('tabindex')).toBe(false);
726+
expect(host.getAttribute('tabindex')).toBe('-1');
727+
});
728+
729+
it('should forward focus to the underlying button when the host is focused', () => {
730+
const fixture = TestBed.createComponent(ButtonToggleWithTabindex);
731+
fixture.detectChanges();
732+
733+
const host = fixture.nativeElement.querySelector('.mat-button-toggle');
734+
const button = host.querySelector('button');
735+
736+
expect(document.activeElement).not.toBe(button);
737+
738+
host.focus();
739+
740+
expect(document.activeElement).toBe(button);
727741
});
728742
});
729743

src/lib/button-toggle/button-toggle.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -365,9 +365,11 @@ export const _MatButtonToggleMixinBase: CanDisableRippleCtor & typeof MatButtonT
365365
'[class.mat-button-toggle-disabled]': 'disabled',
366366
'[class.mat-button-toggle-appearance-standard]': 'appearance === "standard"',
367367
'class': 'mat-button-toggle',
368-
// Clear out the native tabindex here since we forward it to the underlying button
369-
'[attr.tabindex]': 'null',
368+
// Always reset the tabindex to -1 so it doesn't conflict with the one on the `button`,
369+
// but can still receive focus from things like cdkFocusInitial.
370+
'[attr.tabindex]': '-1',
370371
'[attr.id]': 'id',
372+
'(focus)': 'focus()',
371373
}
372374
})
373375
export class MatButtonToggle extends _MatButtonToggleMixinBase implements OnInit,

0 commit comments

Comments
 (0)