0

So I am struggling with adding radio buttons to my reactive form in my angular app. I am using the material radio buttons and there are two choices: one is client and one is trainer.

They look ok but unfortunately when I try to submit the form I notice that the value of the radio button form control is null despite the fact that I had selected a value. Can someone see what I did wrong?

the sign in template

<h2 class="title">Sign in!</h2>

<form [formGroup]="signInForm" (ngSubmit)="onSubmit()">
  <mat-radio-group aria-label="Select an option">
    <mat-radio-button formGroupName="type" value="trainer">Trainer</mat-radio-button>
    <mat-radio-button formGroupName="type" value="client">Client</mat-radio-button>
  </mat-radio-group>
  <div class="form-group">
    <label for="exampleInputEmail1">Email address</label>
    <input type="email" class="form-control" formControlName="email" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
  </div>
  <div class="form-group">
    <label for="exampleInputPassword1">Password</label>
    <input type="password" formControlName="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

Component code that handles the form

ngOnInit() {
    this.signInForm = new FormGroup({
      email: new FormControl(null, [
        Validators.email,
        Validators.required]),
      password: new FormControl( null, [
        Validators.required
      ]),
      type: new FormControl(null)
    });
  }


 onSubmit() {
    console.log('valid form', this.signInForm.valid);
    this.getFormValidationErrors();
    const data = {
      email: this.signInForm.value.email,
      password: this.signInForm.value.password,
      type: this.signInForm.value.type
    };
    console.log('type6', data);

    this.authService.signIn(data)
      .subscribe((res) => {
        console.log('RES');
      });
  }

This is what it looks like, there's a console.log of the for data in the console on the right side. As you can see the control 'type' has value null

enter image description here

2
  • It would help a lot if you could add rest of the code to stackblitz Commented Apr 5, 2019 at 23:01
  • you must use FormControlName ="type", NOT formGroupName Commented Apr 6, 2019 at 12:49

1 Answer 1

1

To achieve this you can use formControlName on mat-radio-group

<mat-radio-group formControlName="type">
 <mat-radio-button value="trainer">Trainer</mat-radio-button>
 <mat-radio-button value="client">Client</mat-radio-button>
</mat-radio-group>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.