How to use Radio Button and set default value with Reactive Form in Angular

In HTML file:

<form [formGroup]="registrationForm" (ngSubmit)="onSubmit()">
  <div class="group-gap">
    <h5 class="mb-3">Gender</h5>
    <div class="d-block my-3">
      <div class="custom-control custom-radio">
        <input id="male" type="radio" class="custom-control-input" value="male" name="gender" formControlName="gender">
        <label class="custom-control-label" for="male">Male</label>
      </div>
      <div class="custom-control custom-radio">
        <input id="female" type="radio" class="custom-control-input" value="female" name="gender" formControlName="gender">
        <label class="custom-control-label" for="female">Female</label>
      </div>
      <div class="invalid-feedback" *ngIf="isSubmitted && myForm.errors?.required">
        <p>Please select either value</p>
      </div>
    </div>
  </div>
    <button type="submit" class="btn btn-danger btn-lg btn-block">Submit</button>
</form>

In ts file.

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


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

export class AppComponent {
  isSubmitted = false;
  constructor(public fb: FormBuilder) { }
  registrationForm = this.fb.group({
    gender: ['male', [Validators.required]] //set default value
  })

  // Getter method to access form control
  get myForm() {
    return this.registrationForm.get('gender');
  }

  // Submit Registration Form
  onSubmit() {
    this.isSubmitted = true;
    if(!this.registrationForm.valid) {
      return false;
    } else {
      alert(JSON.stringify(this.registrationForm.value))
    }
  }  

}

Leave a Reply

Your email address will not be published. Required fields are marked *