Angular Radio Buttons Demo with Reactive Forms

In this tutorial, we will create a reactive form in Angular which contains radio buttons as its form controls.

For demonstration purposes, we have created a form group named userForm which contains three form controls firstName, lastName and gender.

The firstName and lastName fields are simple text fields, whereas the gender field is a radio button.

To show the options of the radio buttons dynamically, we have defined a genders array in our ts file which contains the value and title of each option of the radio button.

Have a look at our ts file:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  genders: any[] = [
    { value: 'Male', title: 'Male' },
    { value: 'Female', title: 'Female' },
    { value: 'Others', title: 'Others' },
  ];

  userForm: FormGroup;
  formData:any;
  isFormSubmitted: boolean = false;;

  constructor(private fb: FormBuilder) {

    this.userForm = this.fb.group({
      'firstName': ['', Validators.required],
      'lastName': ['', Validators.required],
      'gender': ['', Validators.required]
    });

  }

  ngOnInit(): void {
  }

  submit(){

    // Get the value of the form
    this.formData = this.userForm.value;

    // To show form data in template(just for demo)
    this.isFormSubmitted = true;

    // Add your stuff
  }
}

…And here is our template file:

 <div class="container">

  <form [formGroup]="userForm">
    <div>
      <input type="text" formControlName="firstName" placeholder="Type here">
      <label> First Name</label>
    </div>
    <div>
      <input type="text" formControlName="lastName" placeholder="Type here">
      <label> Last Name</label>
    </div>

    <div>
      <span>Select Gender</span><br>
      <div *ngFor="let gender of genders">
        <input type="radio" name="gender" [value]="gender.value" formControlName="gender">
        <label>{{gender.title}}</label>
      </div>
    </div>

    <button type="submit" (click)="submit()" [disabled]="userForm.invalid">Submit</button>

    <!-- Show form data on submission(just for demonstration) -->
    <p *ngIf="isFormSubmitted">Form Data: {{formData | json}}</p>
  </form>

</div> 

Output:

Angular Radio Buttons Demo with Reactive Forms

Please note that the submit button remains disabled until the user fills/selects all the mandatory fields.

That’s because we have bind the disabled property of the button with the invalid property of the reactive form.

The invalid property returns true if the form is invalid and returns false if the form is valid.

That’s all for this article. Thanks for reading!