Angular Radio Button example is demonstrated in this post.
First, generate a radio button component and html template using the ng g c radioButton command.
C:\AngularWorkspace\RadioButton> ng g c radioButton
CREATE src/app/radio-button/radio-button.component.html (27 bytes)
CREATE src/app/radio-button/radio-button.component.spec.ts (664 bytes)
CREATE src/app/radio-button/radio-button.component.ts (293 bytes)
CREATE src/app/radio-button/radio-button.component.scss (0 bytes)
In the previous post, we had discussed the checkbox example in various ways.
Radio Button Reactive Form Example
The radio button is described using reactive forms.
radio-button.component.ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-radio-button',
templateUrl: './radio-button.component.html',
styleUrls: ['./radio-button.component.scss']
})
export class RadioButtonComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
gender: ['male']
})
}
submit() {
alert(JSON.stringify(this.form.value))
}
}
In the radio button component's submit method the form value and its label are displayed in JSON format in browser window using alert() method. The alert() method can also be replaced with console.log() to see it in browser console.
radio-button.component.html
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-radio-button',
templateUrl: './radio-button.component.html',
styleUrls: ['./radio-button.component.scss']
})
export class RadioButtonComponent {
form: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.form = this.formBuilder.group({
gender: ['male']
})
}
submit() {
alert(JSON.stringify(this.form.value))
}
}
If you define the formControlName, the name and formControlname should be same. Otherwise, you will get the following error in console on compilation.
RadioButtonComponent.html:4 ERROR Error:
If you define both a name and a formControlName attribute on your radio button, their values
must match. Ex:
<input type="radio" formControlName="food" name="food">
Run the above example using ng serve to see the following output,