温馨提示×

Angular怎么实现radio单选框

小亿
99
2024-01-22 10:27:02
栏目: 编程语言

在Angular中实现radio单选框,你可以使用[(ngModel)]指令来绑定一个变量到radio按钮上,并使用name属性来将radio按钮分组。

以下是一个简单的示例:

<label>
  <input type="radio" [(ngModel)]="selectedOption" name="options" value="option1">
  Option 1
</label>

<label>
  <input type="radio" [(ngModel)]="selectedOption" name="options" value="option2">
  Option 2
</label>

<label>
  <input type="radio" [(ngModel)]="selectedOption" name="options" value="option3">
  Option 3
</label>

<p>Selected option: {{ selectedOption }}</p>

在组件类中,你需要定义一个selectedOption变量来存储选中的选项:

import { Component } from '@angular/core';

@Component({
  selector: 'app-radio',
  templateUrl: './radio.component.html',
  styleUrls: ['./radio.component.css']
})
export class RadioComponent {
  selectedOption: string;
}

当用户选择一个选项时,selectedOption变量会自动更新为选中的值,并且可以在模板中通过插值表达式显示出来。

这样,你就实现了一个基本的radio单选框。

0