Skip to content

Commit 4962c1d

Browse files
committed
feat(tabs): add method for programmatically setting focus
Adds a method that allows for focus to be moved to a particular tab. This is usually tricky, because all of the DOM elements are hidden away inside the tab group template. Fixes #15007.
1 parent aff565a commit 4962c1d

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {By} from '@angular/platform-browser';
66
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
77
import {CommonModule} from '@angular/common';
88
import {Observable} from 'rxjs';
9-
import {MatTab, MatTabGroup, MatTabHeaderPosition, MatTabsModule} from './index';
9+
import {MatTab, MatTabGroup, MatTabHeaderPosition, MatTabsModule, MatTabHeader} from './index';
1010

1111

1212
describe('MatTabGroup', () => {
@@ -277,6 +277,21 @@ describe('MatTabGroup', () => {
277277
.toHaveBeenCalledWith(jasmine.objectContaining({index: 0}));
278278
});
279279

280+
it('should be able to programmatically focus a particular tab', () => {
281+
fixture.detectChanges();
282+
const tabGroup: MatTabGroup =
283+
fixture.debugElement.query(By.css('mat-tab-group')).componentInstance;
284+
const tabHeader: MatTabHeader =
285+
fixture.debugElement.query(By.css('mat-tab-header')).componentInstance;
286+
287+
expect(tabHeader.focusIndex).not.toBe(3);
288+
289+
tabGroup.focusTab(3);
290+
fixture.detectChanges();
291+
292+
expect(tabHeader.focusIndex).not.toBe(3);
293+
});
294+
280295
});
281296

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

src/lib/tabs/tab-group.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,18 @@ export class MatTabGroup extends _MatTabGroupMixinBase implements AfterContentIn
267267
}
268268
}
269269

270+
/**
271+
* Sets focus to a particular tab.
272+
* @param index Index of the tab to be focused.
273+
*/
274+
focusTab(index: number) {
275+
const header = this._tabHeader;
276+
277+
if (header) {
278+
header.focusIndex = index;
279+
}
280+
}
281+
270282
_focusChanged(index: number) {
271283
this.focusChange.emit(this._createChangeEvent(index));
272284
}

tools/public_api_guard/lib/tabs.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@ export declare class MatTabGroup extends _MatTabGroupMixinBase implements AfterC
9898
_handleClick(tab: MatTab, tabHeader: MatTabHeader, index: number): void;
9999
_removeTabBodyWrapperHeight(): void;
100100
_setTabBodyWrapperHeight(tabHeight: number): void;
101+
focusTab(index: number): void;
101102
ngAfterContentChecked(): void;
102103
ngAfterContentInit(): void;
103104
ngOnDestroy(): void;

0 commit comments

Comments
 (0)