Skip to content

Commit

Permalink
feat(tabs): add method for programmatically setting focus
Browse files Browse the repository at this point in the history
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 angular#15007.
  • Loading branch information
crisbeto committed May 26, 2019
1 parent eef132b commit 7089f50
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/material/tabs/tab-group.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {By} from '@angular/platform-browser';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {CommonModule} from '@angular/common';
import {Observable} from 'rxjs';
import {MatTab, MatTabGroup, MatTabHeaderPosition, MatTabsModule} from './index';
import {MatTab, MatTabGroup, MatTabHeaderPosition, MatTabsModule, MatTabHeader} from './index';


describe('MatTabGroup', () => {
Expand Down Expand Up @@ -277,6 +277,21 @@ describe('MatTabGroup', () => {
.toHaveBeenCalledWith(jasmine.objectContaining({index: 0}));
});

it('should be able to programmatically focus a particular tab', () => {
fixture.detectChanges();
const tabGroup: MatTabGroup =
fixture.debugElement.query(By.css('mat-tab-group')).componentInstance;
const tabHeader: MatTabHeader =
fixture.debugElement.query(By.css('mat-tab-header')).componentInstance;

expect(tabHeader.focusIndex).not.toBe(3);

tabGroup.focusTab(3);
fixture.detectChanges();

expect(tabHeader.focusIndex).not.toBe(3);
});

});

describe('aria labelling', () => {
Expand Down
12 changes: 12 additions & 0 deletions src/material/tabs/tab-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,18 @@ export class MatTabGroup extends _MatTabGroupMixinBase implements AfterContentIn
}
}

/**
* Sets focus to a particular tab.
* @param index Index of the tab to be focused.
*/
focusTab(index: number) {
const header = this._tabHeader;

if (header) {
header.focusIndex = index;
}
}

_focusChanged(index: number) {
this.focusChange.emit(this._createChangeEvent(index));
}
Expand Down
1 change: 1 addition & 0 deletions tools/public_api_guard/material/tabs.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export declare class MatTabGroup extends _MatTabGroupMixinBase implements AfterC
_handleClick(tab: MatTab, tabHeader: MatTabHeader, index: number): void;
_removeTabBodyWrapperHeight(): void;
_setTabBodyWrapperHeight(tabHeight: number): void;
focusTab(index: number): void;
ngAfterContentChecked(): void;
ngAfterContentInit(): void;
ngOnDestroy(): void;
Expand Down

0 comments on commit 7089f50

Please sign in to comment.