Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular how to default set radio buttons, Reactive forms

Implementing a reactive form in Angular with radio buttons. I want to set a default value, I have tried the following:

Template:

<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>

Model:

  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?

like image 856
Willem van der Veen Avatar asked Jan 29 '23 01:01

Willem van der Veen


1 Answers

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 */ }
}
like image 121
Felix Lemke Avatar answered Feb 04 '23 12:02

Felix Lemke