Angular Material 单选按钮

17 Mar 2025 | 阅读 2 分钟

<mat-radiobutton> 用于 <input type="radio"> 以增强基于 Material Design 的样式。它提供了与 <input type="radio"> 相同的功能,并具有 Angular Material Design 样式动画

单选按钮标签

单选按钮标签作为 <mat-radiobutton> 元素的内容提供。如果您不希望标签出现在单选按钮旁边,则可以使用 area-label 指定相应的标签。

单选按钮组

单选按钮应放置在 <mat-radio-group> 中,除非 DOM 结构使得无法做到这一点(例如,表格单元格内的单选按钮)。单选按钮组中的不同单选按钮将继承组名。

与 @angular/forms 一起使用

<mat-radio-group> 与 @angular/forms 兼容,并支持 ReactiveFormsModule

可访问性

<Mat-radio-button> 使用内部 <input type = "radio"> 提供可访问的体验。这个内部单选按钮接收焦点,并自动标记 <mat-radio-button> 元素的文本内容。

单选按钮组必须通过 area-label 或 area-labelledby 获得有意义的标签。

默认颜色配置

单选按钮的默认颜色通过使用 MAT_RADIO_DEFAULT_OPTIONS 提供程序全局配置。

示例:1

app.component.html

app.component.ts

app.component.css

输出

Angular Material Radio Button

如果出现同名的单选按钮,则一次只能选择一个。

示例 2

app.module.ts

以下是修改后的 CSS 文件 app.component.css

app.component.ts

app.component.ts

以下是 HTML 主机文件 app.component.html

输出

Angular Material Radio Button

说明

首先,我们使用 mat-radio-group 创建了一个单选按钮组,并与 ngModel 绑定。然后,我们使用 mat-radio-button 添加了单选按钮。