You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular Material应用中默认选中单选组首个选项?

Angular中mat-radio-group默认选中第一个选项的最简可靠实现

方案1:模板驱动表单

  1. 组件类中定义选项集合与绑定变量,初始化时选中第一个选项:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-radio-example',
  templateUrl: './radio-example.component.html'
})
export class RadioExampleComponent implements OnInit {
  radioOptions = ['选项A', '选项B', '选项C'];
  selectedOption: string;

  ngOnInit(): void {
    // 数组非空时赋值,避免报错
    this.selectedOption = this.radioOptions.length ? this.radioOptions[0] : '';
  }
}
  1. 模板通过ngModel绑定变量:
<mat-radio-group [(ngModel)]="selectedOption">
  <mat-radio-button 
    *ngFor="let option of radioOptions" 
    [value]="option"
  >
    {{ option }}
  </mat-radio-button>
</mat-radio-group>

方案2:响应式表单

  1. 组件类中用FormBuilder创建表单时,直接将第一个选项设为控件初始值:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-radio-reactive',
  templateUrl: './radio-reactive.component.html'
})
export class RadioReactiveComponent implements OnInit {
  radioOptions = ['选项X', '选项Y', '选项Z'];
  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.form = this.fb.group({
      radioControl: [this.radioOptions.length ? this.radioOptions[0] : '']
    });
  }
}
  1. 模板通过formControlName绑定表单控件:
<form [formGroup]="form">
  <mat-radio-group formControlName="radioControl">
    <mat-radio-button 
      *ngFor="let option of radioOptions" 
      [value]="option"
    >
      {{ option }}
    </mat-radio-button>
  </mat-radio-group>
</form>

关键注意事项

  • 若选项是对象类型,需用[ngValue]替代[value]绑定对象,初始值要对应数组第一个对象实例:
    radioOptions = [{id: 1, name: '选项1'}, {id: 2, name: '选项2'}];
    // 模板驱动:this.selectedOption = this.radioOptions[0];
    // 响应式:radioControl: [this.radioOptions[0]]
    
  • 必须添加数组非空判断,避免数组为空时radioOptions[0]抛出undefined错误。

内容的提问来源于stack exchange,提问作者Razvan Zamfir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 23:01:03