Skip to content

feat(cdk-experimental/radio): add radio demo to dev-app #31180

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 5 commits into from
May 21, 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
8 changes: 8 additions & 0 deletions src/cdk-experimental/radio/radio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,14 @@ describe('CdkRadioGroup', () => {
setupRadioGroup({options: []});
expect(radioButtons.length).toBe(0);
});

describe('bad accessibility violations', () => {
it('should report when the selected radio button is disabled and skipDisabled is true', () => {
spyOn(console, 'error');
setupRadioGroup({value: 1, skipDisabled: true, disabledOptions: [1]});
expect(console.error).toHaveBeenCalled();
});
});
});
});

Expand Down
9 changes: 9 additions & 0 deletions src/cdk-experimental/radio/radio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,15 @@ export class CdkRadioGroup<V> {
private _hasFocused = signal(false);

constructor() {
afterRenderEffect(() => {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
const violations = this.pattern.validate();
for (const violation of violations) {
console.error(violation);
}
}
});

afterRenderEffect(() => {
if (!this._hasFocused()) {
this.pattern.setDefaultState();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.dev/license
*/

import {signal} from '@angular/core';
import {computed, signal} from '@angular/core';
import {SignalLike, WritableSignalLike} from '../signal-like/signal-like';
import {ListFocus, ListFocusInputs, ListFocusItem} from '../list-focus/list-focus';

Expand Down Expand Up @@ -36,6 +36,11 @@ export class ListSelection<T extends ListSelectionItem<V>, V> {
/** The end index to use for range selection. */
rangeEndIndex = signal<number>(0);

/** The currently selected items. */
selectedItems = computed(() =>
this.inputs.items().filter(item => this.inputs.value().includes(item.value())),
);

constructor(readonly inputs: ListSelectionInputs<T, V> & {focusManager: ListFocus<T>}) {}

/** Selects the item at the current active index. */
Expand Down
19 changes: 17 additions & 2 deletions src/cdk-experimental/ui-patterns/radio/radio-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,11 @@ export class RadioGroupPattern<V> {
/** Whether the radio group is disabled. */
disabled = computed(() => this.inputs.disabled() || this.focusManager.isListDisabled());

/** The currently selected radio button. */
selectedItem = computed(() => this.selection.selectedItems()[0]);

/** Whether the radio group is readonly. */
readonly: SignalLike<boolean>;
readonly = computed(() => this.selectedItem()?.disabled() || this.inputs.readonly());

/** The tabindex of the radio group (if using activedescendant). */
tabindex = computed(() => this.focusManager.getListTabindex());
Expand Down Expand Up @@ -111,7 +114,6 @@ export class RadioGroupPattern<V> {
});

constructor(readonly inputs: RadioGroupInputs<V>) {
this.readonly = inputs.readonly;
this.orientation = inputs.orientation;

this.focusManager = new ListFocus(inputs);
Expand Down Expand Up @@ -194,6 +196,19 @@ export class RadioGroupPattern<V> {
}
}

/** Validates the state of the radio group and returns a list of accessibility violations. */
validate(): string[] {
const violations: string[] = [];

if (this.selectedItem()?.disabled() && this.inputs.skipDisabled()) {
violations.push(
"Accessibility Violation: The selected radio button is disabled while 'skipDisabled' is true, making the selection unreachable via keyboard.",
);
}

return violations;
}

/** Safely performs a navigation operation and updates selection if needed. */
private _navigate(opts: SelectOptions = {}, operation: () => boolean) {
const moved = operation();
Expand Down
12 changes: 12 additions & 0 deletions src/cdk-experimental/ui-patterns/radio/radio.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,4 +298,16 @@ describe('RadioGroup Pattern', () => {
expect(radioGroup.inputs.activeIndex()).toBe(0); // Defaults to first focusable
});
});

describe('validate', () => {
it('should report a violation if the selected item is disabled and skipDisabled is true', () => {
const {radioGroup, radioButtons} = getDefaultPatterns({
value: signal(['Banana']),
skipDisabled: signal(true),
});
radioButtons[1].disabled.set(true); // Disable the selected item.
const violations = radioGroup.validate();
expect(violations.length).toBe(1);
});
});
});
29 changes: 29 additions & 0 deletions src/components-examples/cdk-experimental/radio/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
load("//tools:defaults.bzl", "ng_project")

package(default_visibility = ["//visibility:public"])

ng_project(
name = "radio",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//:node_modules/@angular/core",
"//:node_modules/@angular/forms",
"//src/cdk-experimental/radio",
"//src/material/checkbox",
"//src/material/form-field",
"//src/material/select",
],
)

filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
.example-radio-controls {
display: flex;
align-items: center;
gap: 16px;
padding-bottom: 16px;
}

.example-radio-group {
gap: 4px;
margin: 0;
padding: 8px;
max-height: 50vh;
border: 1px solid var(--mat-sys-outline);
border-radius: var(--mat-sys-corner-extra-small);
display: flex;
list-style: none;
flex-direction: column;
overflow: scroll;
user-select: none;
}

.example-radio-group[aria-orientation='horizontal'] {
flex-direction: row;
}

.example-radio-group[aria-disabled='true'] {
background-color: var(--mat-sys-surface-dim);
pointer-events: none;
}

.example-radio-button {
gap: 16px;
padding: 16px;
display: flex;
cursor: pointer;
position: relative;
align-items: center;
border-radius: var(--mat-sys-corner-extra-small);
}

/* Basic visual indicator for the radio button */
.example-radio-indicator {
width: 16px;
height: 16px;
border-radius: 50%;
border: 2px solid var(--mat-sys-outline);
display: inline-block;
position: relative;
}

.example-radio-button[aria-checked='true'] .example-radio-indicator {
border-color: var(--mat-sys-primary);
}

.example-radio-button[aria-checked='true'] .example-radio-indicator::after {
content: '';
display: block;
width: 8px;
height: 8px;
border-radius: 50%;
background-color: var(--mat-sys-primary);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

.example-radio-button[aria-disabled='true'][aria-checked='true'] .example-radio-indicator::after {
background-color: var(--mat-sys-outline);
}

.example-radio-button.cdk-active,
.example-radio-button[aria-disabled='false']:hover {
outline: 1px solid var(--mat-sys-outline);
background: var(--mat-sys-surface-container);
}

.example-radio-button[aria-disabled='false']:focus-within {
outline: 2px solid var(--mat-sys-primary);
background: var(--mat-sys-surface-container);
}

.example-radio-button.cdk-active[aria-disabled='true'],
.example-radio-button[aria-disabled='true']:focus-within {
outline: 2px solid var(--mat-sys-outline);
}

.example-radio-button[aria-disabled='true'] {
cursor: default;
}

.example-radio-button[aria-disabled='true'] span:not(.example-radio-indicator) {
opacity: 0.3;
}

.example-radio-button[aria-disabled='true']::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
border-radius: var(--mat-sys-corner-extra-small);
background-color: var(--mat-sys-on-surface);
opacity: var(--mat-sys-focus-state-layer-opacity);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<div class="example-radio-controls">
<mat-checkbox [formControl]="disabled">Disabled</mat-checkbox>
<mat-checkbox [formControl]="readonly">Readonly</mat-checkbox>
<mat-checkbox [formControl]="skipDisabled">Skip Disabled</mat-checkbox>

<mat-form-field subscriptSizing="dynamic" appearance="outline">
<mat-label>Selected Flavor</mat-label>
<mat-select [(value)]="selectedValue">
<mat-option [value]="null"><em>None</em></mat-option>
@for (flavor of flavors; track flavor) {
<mat-option [value]="flavor">{{flavor}}</mat-option>
}
</mat-select>
</mat-form-field>

<mat-form-field subscriptSizing="dynamic" appearance="outline">
<mat-label>Disabled Radio Options</mat-label>
<mat-select [(value)]="disabledOptions" multiple>
@for (flavor of flavors; track flavor) {
<mat-option [value]="flavor">{{flavor}}</mat-option>
}
</mat-select>
</mat-form-field>

<mat-form-field subscriptSizing="dynamic" appearance="outline">
<mat-label>Orientation</mat-label>
<mat-select [(value)]="orientation">
<mat-option value="vertical">Vertical</mat-option>
<mat-option value="horizontal">Horizontal</mat-option>
</mat-select>
</mat-form-field>

<mat-form-field subscriptSizing="dynamic" appearance="outline">
<mat-label>Focus strategy</mat-label>
<mat-select [(value)]="focusMode">
<mat-option value="roving">Roving Tabindex</mat-option>
<mat-option value="activedescendant">Active Descendant</mat-option>
</mat-select>
</mat-form-field>
</div>

<!-- #docregion radio-group -->
<ul
cdkRadioGroup
[(value)]="selectedValue"
[disabled]="disabled.value"
[readonly]="readonly.value"
[skipDisabled]="skipDisabled.value"
[orientation]="orientation"
[focusMode]="focusMode"
class="example-radio-group"
aria-label="Select your favorite ice cream flavor"
>
@for (flavor of flavors; track flavor) {
@let optionDisabled = disabledOptions.includes(flavor);
<li cdkRadioButton [value]="flavor" [disabled]="optionDisabled" class="example-radio-button">
<span class="example-radio-indicator"></span>
<span>{{ flavor }}</span>
</li>
}
</ul>
<!-- #enddocregion radio-group -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {Component} from '@angular/core';
import {CdkRadioGroup, CdkRadioButton} from '@angular/cdk-experimental/radio';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatSelectModule} from '@angular/material/select';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';

/** @title Basic CDK Radio Group */
@Component({
selector: 'cdk-radio-example',
exportAs: 'cdkRadioExample',
templateUrl: 'cdk-radio-example.html',
styleUrl: 'cdk-radio-example.css',
standalone: true,
imports: [
CdkRadioGroup,
CdkRadioButton,
MatCheckboxModule,
MatFormFieldModule,
MatSelectModule,
FormsModule,
ReactiveFormsModule,
],
})
export class CdkRadioExample {
orientation: 'vertical' | 'horizontal' = 'vertical';
disabled = new FormControl(false, {nonNullable: true});

flavors = ['Vanilla', 'Chocolate', 'Strawberry', 'Mint Chip', 'Cookies & Cream', 'Rocky Road'];

// New controls
readonly = new FormControl(false, {nonNullable: true});
skipDisabled = new FormControl(true, {nonNullable: true});
focusMode: 'roving' | 'activedescendant' = 'roving';
selectedValue: string | null = 'Vanilla'; // To control/reflect the radio group's value

// Control for which radio options are individually disabled
disabledOptions: string[] = ['Chocolate'];
}
1 change: 1 addition & 0 deletions src/components-examples/cdk-experimental/radio/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {CdkRadioExample} from './cdk-radio/cdk-radio-example';
5 changes: 3 additions & 2 deletions src/dev-app/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
load("//tools:defaults.bzl", "http_server", "ng_project", "sass_binary")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("@aspect_rules_esbuild//esbuild:defs.bzl", "esbuild")
load("@aspect_rules_js//npm:defs.bzl", "npm_package")
load("@npm//:defs.bzl", "npm_link_all_packages")
load("//src/components-examples:config.bzl", "ALL_EXAMPLES")
load("//tools:defaults.bzl", "http_server", "ng_project", "sass_binary")

package(default_visibility = ["//visibility:public"])

Expand Down Expand Up @@ -36,6 +36,7 @@ ng_project(
"//src/dev-app/cdk-experimental-accordion",
"//src/dev-app/cdk-experimental-combobox",
"//src/dev-app/cdk-experimental-listbox",
"//src/dev-app/cdk-experimental-radio",
"//src/dev-app/cdk-experimental-tabs",
"//src/dev-app/cdk-listbox",
"//src/dev-app/cdk-menu",
Expand Down
21 changes: 21 additions & 0 deletions src/dev-app/cdk-experimental-radio/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
load("//tools:defaults.bzl", "ng_project")

package(default_visibility = ["//visibility:public"])

ng_project(
name = "cdk-experimental-radio",
srcs = glob(["**/*.ts"]),
assets = ["cdk-radio-demo.html"],
deps = [
"//:node_modules/@angular/core",
"//src/components-examples/cdk-experimental/radio",
],
)

filegroup(
name = "source-files",
srcs = glob([
"**/*.ts",
"**/*.html",
]),
)
4 changes: 4 additions & 0 deletions src/dev-app/cdk-experimental-radio/cdk-radio-demo.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<div>
<h4>Radio using UI Patterns</h4>
<cdk-radio-example></cdk-radio-example>
</div>
Loading
Loading