Open ghost opened 3 years ago
I came across this problem today. Looking at the documentation page, need some javascript to make tabs work.
In the HTML, before the closing body tag, add
<script src="script.js"></script>
Then in script.js, add
document.addEventListener("DOMContentLoaded", function() {
const tabs = document.querySelectorAll("menu[role=tablist]");
for (let i = 0; i < tabs.length; i++) {
const tab = tabs[i];
const tabButtons = tab.querySelectorAll("menu[role=tablist] > button");
tabButtons.forEach((btn) =>
btn.addEventListener("click", (e) => {
e.preventDefault();
tabButtons.forEach((button) => {
if (
button.getAttribute("aria-controls") ===
e.target.getAttribute("aria-controls")
) {
button.setAttribute("aria-selected", true);
openTab(e, tab);
} else {
button.setAttribute("aria-selected", false);
}
});
})
);
}
});
function openTab(event, tab) {
const articles = tab.parentNode.querySelectorAll('[role="tabpanel"]');
articles.forEach((p) => {
p.setAttribute("hidden", true);
});
const article = tab.parentNode.querySelector(
`[role="tabpanel"]#${event.target.getAttribute("aria-controls")}`
);
article.removeAttribute("hidden");
}
For anyone using Angular, I'm using the following solution:
<article>
section: windowTabs: WindowTab[] = [{
id: 'tab-banana',
title: 'Banana',
selected: true,
component: BananaComponent
}, {
id: 'tab-apple',
title: 'Apple',
selected: false,
component: AppleComponent
},
// ...
];
Here's the interface WindowTab
used for typing:
export interface WindowTab {
id: string,
title: string,
selected: boolean,
component: any
}
changeSelectedTab(selectedTab: WindowTab): void {
if (selectedTab.selected)
return;
this.windowTabs.forEach(tab => {
tab.selected = selectedTab.id === tab.id
})
}
<div class="window-body">
<section class="tabs">
<menu role="tablist" aria-label="Sample tabs">
<ng-container *ngFor="let tab of windowTabs">
<button
role="tab"
[attr.aria-controls]="tab.id"
[attr.aria-selected]="tab.selected"
(click)="this.changeSelectedTab(tab)"
>
{{tab.title}}
</button>
</ng-container>
</menu>
<ng-container *ngFor="let tab of windowTabs">
<article
role="tabpanel"
[id]="tab.id"
[hidden]="!tab.selected"
>
<ng-template [ngComponentOutlet]="tab.component"></ng-template>
</article>
</ng-container>
</section>
</div>
This will dynamically create the tabs, assign the function to switch to a tab, and also render its component when it gets clicked. Hope it helps anyone.
When viewing this, it won't switch tabs or tabpanels.
This also won't let you interact with the tabs at all.