Implementing a reactive form in Angular with radio buttons. I want to set a default value, I have tried the following:
<form [formGroup]="form" (ngSubmit)="onSubmit(form)" class="actionsForm">
    <input type="radio" id="entertainCrowdSkill1" [value]="skillsForBackend[0]"
    class="radiobuttons" formControlName="skill" [checked]="true">
    <input type="radio" id="entertainCrowdSkill2" [value]="skillsForBackend[1]" 
    class="radiobuttons" formControlName="skill">
</form>
  ngOnInit() {
    this.form = this.fb.group({
      skill: ['', Validators.required],
    });
  }
  onSubmit(form) {
    console.log(form.controls.skill.value) // logs empty string
}
The button appears to be checked even the CSS:checked class is applied. However, when I try to log the value of skill it is an empty string (the default value entered in the fb). I have seen an answer but this was for template driven forms.
How do I set a default value for the radio buttons in the template in a reactive form?
Assign the initial value with the FormBuilder group contructor instead of using [checked]. You assigned the value '', which is an empty string. To execute the onSubmit function add (ngSubmit)="onSubmit()" to the form tag.
<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input type="radio" formControlName="skill" [value]="skillsForBackend[0]">
  <input type="radio" formControlName="skill" [value]="skillsForBackend[1]">
</form>
In your typescript try the following.
ngOnInit() {
  this.form = this.fb.group({
    skill: [this.skillsForBackend[0], Validators.required]
  });
}
onSubmit() {
  console.log(this.form.value) // should show { skill: /* your data */ }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With