Skip to content

fix(material/tabs): allow ID to be set on tab #30768

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions goldens/material/tabs/index.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export class MatTab implements OnInit, OnChanges, OnDestroy {
_closestTabGroup: any;
get content(): TemplatePortal | null;
disabled: boolean;
id: string | null;
_implicitContent: TemplateRef<any>;
isActive: boolean;
labelClass: string | string[];
Expand All @@ -170,7 +171,7 @@ export class MatTab implements OnInit, OnChanges, OnDestroy {
set templateLabel(value: MatTabLabel);
textLabel: string;
// (undocumented)
static ɵcmp: i0.ɵɵComponentDeclaration<MatTab, "mat-tab", ["matTab"], { "disabled": { "alias": "disabled"; "required": false; }; "textLabel": { "alias": "label"; "required": false; }; "ariaLabel": { "alias": "aria-label"; "required": false; }; "ariaLabelledby": { "alias": "aria-labelledby"; "required": false; }; "labelClass": { "alias": "labelClass"; "required": false; }; "bodyClass": { "alias": "bodyClass"; "required": false; }; }, {}, ["templateLabel", "_explicitContent"], ["*"], true, never>;
static ɵcmp: i0.ɵɵComponentDeclaration<MatTab, "mat-tab", ["matTab"], { "disabled": { "alias": "disabled"; "required": false; }; "textLabel": { "alias": "label"; "required": false; }; "ariaLabel": { "alias": "aria-label"; "required": false; }; "ariaLabelledby": { "alias": "aria-labelledby"; "required": false; }; "labelClass": { "alias": "labelClass"; "required": false; }; "bodyClass": { "alias": "bodyClass"; "required": false; }; "id": { "alias": "id"; "required": false; }; }, {}, ["templateLabel", "_explicitContent"], ["*"], true, never>;
// (undocumented)
static ɵfac: i0.ɵɵFactoryDeclaration<MatTab, never>;
}
Expand Down Expand Up @@ -267,9 +268,9 @@ export class MatTabGroup implements AfterViewInit, AfterContentInit, AfterConten
// (undocumented)
_focusChanged(index: number): void;
focusTab(index: number): void;
_getTabContentId(i: number): string;
_getTabContentId(index: number): string;
_getTabIndex(index: number): number;
_getTabLabelId(i: number): string;
_getTabLabelId(tab: MatTab, index: number): string;
_handleClick(tab: MatTab, tabHeader: MatTabGroupBaseHeader, index: number): void;
headerPosition: MatTabHeaderPosition;
protected _isServer: boolean;
Expand Down
20 changes: 10 additions & 10 deletions src/material/tabs/tab-group.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,26 @@
(indexFocused)="_focusChanged($event)"
(selectFocusedIndex)="selectedIndex = $event">

@for (tab of _tabs; track tab; let i = $index) {
@for (tab of _tabs; track tab) {
<div class="mdc-tab mat-mdc-tab mat-focus-indicator"
#tabNode
role="tab"
matTabLabelWrapper
cdkMonitorElementFocus
[id]="_getTabLabelId(i)"
[attr.tabIndex]="_getTabIndex(i)"
[attr.aria-posinset]="i + 1"
[id]="_getTabLabelId(tab, $index)"
[attr.tabIndex]="_getTabIndex($index)"
[attr.aria-posinset]="$index + 1"
[attr.aria-setsize]="_tabs.length"
[attr.aria-controls]="_getTabContentId(i)"
[attr.aria-selected]="selectedIndex === i"
[attr.aria-controls]="_getTabContentId($index)"
[attr.aria-selected]="selectedIndex === $index"
[attr.aria-label]="tab.ariaLabel || null"
[attr.aria-labelledby]="(!tab.ariaLabel && tab.ariaLabelledby) ? tab.ariaLabelledby : null"
[class.mdc-tab--active]="selectedIndex === i"
[class.mdc-tab--active]="selectedIndex === $index"
[class]="tab.labelClass"
[disabled]="tab.disabled"
[fitInkBarToContent]="fitInkBarToContent"
(click)="_handleClick(tab, tabHeader, i)"
(cdkFocusChange)="_tabFocusChanged($event, i)">
(click)="_handleClick(tab, tabHeader, $index)"
(cdkFocusChange)="_tabFocusChanged($event, $index)">
<span class="mdc-tab__ripple"></span>

<!-- Needs to be a separate element, because we can't put
Expand Down Expand Up @@ -71,7 +71,7 @@
<mat-tab-body role="tabpanel"
[id]="_getTabContentId($index)"
[attr.tabindex]="(contentTabIndex != null && selectedIndex === $index) ? contentTabIndex : null"
[attr.aria-labelledby]="_getTabLabelId($index)"
[attr.aria-labelledby]="_getTabLabelId(tab, $index)"
[attr.aria-hidden]="selectedIndex !== $index"
[class]="tab.bodyClass"
[content]="tab.content!"
Expand Down
42 changes: 41 additions & 1 deletion src/material/tabs/tab-group.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,45 @@ describe('MatTabGroup', () => {
fixture.detectChanges();
expect(tabList.hasAttribute('aria-labelledby')).toBe(false);
}));

it('should set IDs on individual tabs and use them to label the tab bodies', () => {
fixture.detectChanges();
const tabs = Array.from<HTMLElement>(fixture.nativeElement.querySelectorAll('.mat-mdc-tab'));
const bodies = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('mat-tab-body'),
);

expect(tabs.length).toBe(3);
expect(bodies.length).toBe(3);
expect(tabs.every(tab => !!tab.getAttribute('id')))
.withContext('All tabs should have IDs')
.toBe(true);
expect(
bodies.every((body, index) => {
const attr = body.getAttribute('aria-labelledby');
return !!attr && tabs[index].getAttribute('id') === attr;
}),
)
.withContext('All tab bodies should be labelled')
.toBe(true);
});

it('should be able to set a custom ID for a tab', () => {
fixture.detectChanges();
const tab = fixture.nativeElement.querySelectorAll('.mat-mdc-tab')[1] as HTMLElement;
const body = fixture.nativeElement.querySelectorAll('mat-tab-body')[1] as HTMLElement;

expect(tab.getAttribute('id')).toBeTruthy();
expect(tab.getAttribute('id')).not.toBe('foo');
expect(body.getAttribute('aria-labelledby')).toBeTruthy();
expect(body.getAttribute('aria-labelledby')).toBe(tab.getAttribute('id'));

fixture.componentInstance.secondTabId = 'foo';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tab.getAttribute('id')).toBe('foo');
expect(body.getAttribute('aria-labelledby')).toBe('foo');
});
});

describe('aria labelling', () => {
Expand Down Expand Up @@ -1236,7 +1275,7 @@ describe('MatTabGroup labels aligned with a config', () => {
<ng-template mat-tab-label>Tab One</ng-template>
Tab one content
</mat-tab>
<mat-tab>
<mat-tab [id]="secondTabId">
<ng-template mat-tab-label>Tab Two</ng-template>
<span>Tab </span><span>two</span><span>content</span>
</mat-tab>
Expand All @@ -1259,6 +1298,7 @@ class SimpleTabsTestApp {
headerPosition: MatTabHeaderPosition = 'above';
ariaLabel: string;
ariaLabelledby: string;
secondTabId: string | null = null;
handleFocus(event: any) {
this.focusEvent = event;
}
Expand Down
8 changes: 4 additions & 4 deletions src/material/tabs/tab-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,13 +497,13 @@ export class MatTabGroup
}

/** Returns a unique id for each tab label element */
_getTabLabelId(i: number): string {
return `${this._groupId}-label-${i}`;
_getTabLabelId(tab: MatTab, index: number): string {
return tab.id || `${this._groupId}-label-${index}`;
}

/** Returns a unique id for each tab content element */
_getTabContentId(i: number): string {
return `${this._groupId}-content-${i}`;
_getTabContentId(index: number): string {
return `${this._groupId}-content-${index}`;
}

/**
Expand Down
9 changes: 9 additions & 0 deletions src/material/tabs/tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ export const MAT_TAB_GROUP = new InjectionToken<any>('MAT_TAB_GROUP');
// This element will be rendered on the server in order to support hydration.
// Hide it so it doesn't cause a layout shift when it's removed on the client.
'hidden': '',

// Clear any custom IDs from the tab since they'll be forwarded to the actual tab.
'[attr.id]': 'null',
},
})
export class MatTab implements OnInit, OnChanges, OnDestroy {
Expand Down Expand Up @@ -99,6 +102,12 @@ export class MatTab implements OnInit, OnChanges, OnDestroy {
/** Classes to be passed to the tab mat-tab-body container. */
@Input() bodyClass: string | string[];

/**
* Custom ID for the tab, overriding the auto-generated one by Material.
* Note that when using this input, it's your responsibility to ensure that the ID is unique.
*/
@Input() id: string | null = null;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is a new input, and no one is currently depending on it, wouldn't it be better if it was a signal input?


/** Portal that will be the hosted content of the tab */
private _contentPortal: TemplatePortal | null = null;

Expand Down
Loading