Skip to content

Commit f20cdab

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 68a2f89 commit f20cdab

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

src/material/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', () => {
@@ -291,6 +291,21 @@ describe('MatTabGroup', () => {
291291
subscription.unsubscribe();
292292
});
293293

294+
it('should be able to programmatically focus a particular tab', () => {
295+
fixture.detectChanges();
296+
const tabGroup: MatTabGroup =
297+
fixture.debugElement.query(By.css('mat-tab-group')).componentInstance;
298+
const tabHeader: MatTabHeader =
299+
fixture.debugElement.query(By.css('mat-tab-header')).componentInstance;
300+
301+
expect(tabHeader.focusIndex).not.toBe(3);
302+
303+
tabGroup.focusTab(3);
304+
fixture.detectChanges();
305+
306+
expect(tabHeader.focusIndex).not.toBe(3);
307+
});
308+
294309
});
295310

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

src/material/tabs/tab-group.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,18 @@ export abstract class _MatTabGroupBase extends _MatTabGroupMixinBase implements
289289
}
290290
}
291291

292+
/**
293+
* Sets focus to a particular tab.
294+
* @param index Index of the tab to be focused.
295+
*/
296+
focusTab(index: number) {
297+
const header = this._tabHeader;
298+
299+
if (header) {
300+
header.focusIndex = index;
301+
}
302+
}
303+
292304
_focusChanged(index: number) {
293305
this.focusChange.emit(this._createChangeEvent(index));
294306
}

tools/public_api_guard/material/tabs.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ export declare abstract class _MatTabGroupBase extends _MatTabGroupMixinBase imp
5858
_handleClick(tab: MatTab, tabHeader: MatTabGroupBaseHeader, index: number): void;
5959
_removeTabBodyWrapperHeight(): void;
6060
_setTabBodyWrapperHeight(tabHeight: number): void;
61+
focusTab(index: number): void;
6162
ngAfterContentChecked(): void;
6263
ngAfterContentInit(): void;
6364
ngOnDestroy(): void;

0 commit comments

Comments
 (0)