Skip to content

Commit 35db331

Browse files
committed
fix(tabs): focus wrapping back to selected label when using shift + tab
Currently the `tabindex` of each of the tab labels is determined by the selected index. This means that if the user tabbed into the header, pressed the right arrow and then pressed shift + tab, their focus would end up on the selected tab. These changes switch to basing the `tabindex` on the focused index which is tied both to the selected index and the user's keyboard navigation.
1 parent 6d7f417 commit 35db331

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

src/lib/tabs/tab-group.spec.ts

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import {LEFT_ARROW} from '@angular/cdk/keycodes';
1+
import {LEFT_ARROW, RIGHT_ARROW} from '@angular/cdk/keycodes';
22
import {dispatchFakeEvent, dispatchKeyboardEvent} from '@angular/cdk/testing';
33
import {Component, OnInit, QueryList, ViewChild, ViewChildren} from '@angular/core';
44
import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
@@ -277,6 +277,22 @@ describe('MatTabGroup', () => {
277277
.toHaveBeenCalledWith(jasmine.objectContaining({index: 0}));
278278
});
279279

280+
it('should update the tabindex of the labels when navigating via keyboard', () => {
281+
fixture.detectChanges();
282+
283+
const tabLabels = fixture.debugElement.queryAll(By.css('.mat-tab-label'))
284+
.map(label => label.nativeElement);
285+
const tabLabelContainer = fixture.debugElement
286+
.query(By.css('.mat-tab-label-container')).nativeElement as HTMLElement;
287+
288+
expect(tabLabels.map(label => label.getAttribute('tabindex'))).toEqual(['0', '-1', '-1']);
289+
290+
dispatchKeyboardEvent(tabLabelContainer, 'keydown', RIGHT_ARROW);
291+
fixture.detectChanges();
292+
293+
expect(tabLabels.map(label => label.getAttribute('tabindex'))).toEqual(['-1', '0', '-1']);
294+
});
295+
280296
});
281297

282298
describe('aria labelling', () => {

src/lib/tabs/tab-group.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -342,10 +342,11 @@ export class MatTabGroup extends _MatTabGroupMixinBase implements AfterContentIn
342342
}
343343

344344
/** Retrieves the tabindex for the tab. */
345-
_getTabIndex(tab: MatTab, idx: number): number | null {
346-
if (tab.disabled) {
345+
_getTabIndex(tab: MatTab, index: number): number | null {
346+
if (tab.disabled || !this._tabHeader) {
347347
return null;
348348
}
349-
return this.selectedIndex === idx ? 0 : -1;
349+
350+
return this._tabHeader.focusIndex === index ? 0 : -1;
350351
}
351352
}

0 commit comments

Comments
 (0)