Angular反应形式的单选按钮值为null

时间:2019-04-05 22:46:21

标签: javascript angular

因此,我很难在我的角度应用程序中将单选按钮添加到我的反应形式中。我使用的是物料单选按钮,有两种选择:一种是客户,一种是培训师。

它们看起来还不错,但是不幸的是,当我尝试提交表单时,尽管我选择了一个值,但我注意到单选按钮表单控件的值为null。有人可以看到我做错了吗?

登录模板

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

处理表单的组件代码

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');
      });
  }

看起来是这样,右侧控制台中有一个用于数据的console.log。如您所见,控件“类型”的值为null

enter image description here

1 个答案:

答案 0 :(得分:1)

要实现此目的,您可以在mat-radio-group上使用formControlName

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