How can Angular implement radio buttons for single selection?
In Angular, to implement radio buttons, you can use the [(ngModel)] directive to bind a variable to the radio button, and use the name attribute to group the radio buttons.
Here is a simple example:
<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>
In the component class, you need to define a selectedOption variable to store the selected option.
import { Component } from '@angular/core';
@Component({
selector: 'app-radio',
templateUrl: './radio.component.html',
styleUrls: ['./radio.component.css']
})
export class RadioComponent {
selectedOption: string;
}
When a user chooses an option, the selectedOption variable will automatically update to the chosen value, which can then be displayed in the template using interpolation.
In this way, you have created a basic radio button.