Angularでは、ラジオボタンの単一選択をどのように実現するのでしょうか?
Angularでラジオボタンを実装する際は、[(ngModel)]ディレクティブを使用して変数をラジオボタンにバインドし、name属性を使用してラジオボタンをグループ化することができます。
以下は簡単な例です:
<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変数が選択された値に自動更新され、テンプレート内で插入式を使用して表示することができます。
これで、基本的なラジオボタンが作成されました。