diff --git a/src/components/calcite-radio-group/calcite-radio-group.e2e.ts b/src/components/calcite-radio-group/calcite-radio-group.e2e.ts index d9ec383b3b1..230722b2260 100644 --- a/src/components/calcite-radio-group/calcite-radio-group.e2e.ts +++ b/src/components/calcite-radio-group/calcite-radio-group.e2e.ts @@ -269,4 +269,36 @@ describe("calcite-radio-group", () => { expect(child2).toEqualAttribute("scale", "m"); expect(child3).toEqualAttribute("scale", "m"); }); + + describe("setFocus()", () => { + it("focuses the first item if there is no selection", async () => { + const page = await newE2EPage({ + html: ` + one + two + three + ` + }); + + const element = await page.find("calcite-radio-group"); + await element.callMethod("setFocus"); + + expect(await page.evaluate(() => document.activeElement.id)).toEqual("child-1"); + }); + + it("focuses the selected item", async () => { + const page = await newE2EPage({ + html: ` + one + two + three + ` + }); + + const element = await page.find("calcite-radio-group"); + await element.callMethod("setFocus"); + + expect(await page.evaluate(() => document.activeElement.id)).toEqual("child-3"); + }); + }); }); diff --git a/src/components/calcite-radio-group/calcite-radio-group.tsx b/src/components/calcite-radio-group/calcite-radio-group.tsx index 1f566dac320..85566e04ceb 100644 --- a/src/components/calcite-radio-group/calcite-radio-group.tsx +++ b/src/components/calcite-radio-group/calcite-radio-group.tsx @@ -8,7 +8,7 @@ import { Prop, Watch, Host, - Build + Build, Method } from "@stencil/core"; import { getElementDir } from "../../utils/dom"; @@ -222,6 +222,18 @@ export class CalciteRadioGroup { @Event() calciteRadioGroupChange: EventEmitter; + // -------------------------------------------------------------------------- + // + // Methods + // + // -------------------------------------------------------------------------- + + /** Focuses the selected item. If there is no selection, it focuses the first item. */ + @Method() + async setFocus() { + (this.selectedItem || this.getItems()[0])?.focus(); + } + //-------------------------------------------------------------------------- // // Private State/Props