2
votes

I'm using reactive form in angular 8, and have a gender toggle radio button. The toggle radio button don't return the value of selected.

html code

<form id="sb-signup-form" method="post" novalidate="" [formGroup]="registerForm" (ngSubmit)="register($event)">
 <div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn btn-primary active">
      <input id="male" type="radio" class="custom-control-input" value="male" name="gender" formControlName="gender"> Male
  </label>
  <label class="btn btn-primary">
      <input id="female" type="radio" class="custom-control-input" value="female" name="gender" formControlName="gender"> Female
  </label>
 </div>
</form>

.ts code

registerForm: FormGroup;
ngOnInit() {
    this.registerForm = this.formBuilder.group({
      gender: ['male']
  });
  }

register(e) {
    console.log(this.registerForm.value);
  }

always the value of gender is 'male', which is the default value.

2

2 Answers

4
votes

This is because of data-toggle="buttons", remove it you will see it work & add active class to label by writing a custom function.

0
votes

Try Like this In HTML file:

<form [formGroup]="form">
   <label>
     <input type="radio" value="Male" formControlName="gender">
       <span>male</span>
   </label>
   <label>
     <input type="radio" value="Female" formControlName="gender">
       <span>female</span>
   </label>
</form>

In the TS file:

form: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = 'Angular2'
    this.form = fb.group({
      gender: ['', Validators.required]
    });
  }