如何以Angular反应形式获取复选框值

时间:2020-03-30 18:43:31

标签: angular typescript angular-reactive-forms angular9

我现在正在学习Angular。我正在制作一个具有一组复选框的反应式表单。我已经使用Angular Material创建了这些复选框。到目前为止,经过一整天的搜索后,我仍然无法提出一种解决方案,该解决方案要求我在TS文件的FormGroup中获得复选框选中的值。我附上代码。

app.component.html

<form [formGroup]="formdata">
   <label>Vehicles</label><br>
   <mat-radio-group>
      <mat-checkbox *ngFor="let v of Vehicles" formControlName="vehicles" [value]="v.value">{{ v.option }}</mat-checkbox>
   </mat-radio-group>
</form>
{{ formdata.value | json }}

app.component.ts

import { FormBuilder } from '@angular/forms';

export interface model
{
  value: string; //Store value for the option
  option: string; //Stores option to be displayed
}

export class FormComponent implements OnInit{
    Vehicles: model[] = [{value: '2 wheelers', option: '2 wheelers'}, {value: '4 wheelers', option: '4 wheelers'}];

    constructor(private fb: FormBuilder) {}
formdata = this.fb.group({
    vehicles: []
});
}

我得到的输出为true or false`` but I want the output as 2或4或2,4`''。

请帮帮我。

1 个答案:

答案 0 :(得分:0)

好吧,您可以单独使用mat-checkbox。请记住,即使没有输入,FormGroup也存在。因此,您可以使用[checked]和(更改)更改formControl的值。

<form [formGroup]="formdata">
   <label>Vehicles</label><br>
   <mat-radio-group>
      <mat-checkbox  
      (change)="formdata.get('vehicles').setValue($event.checked?2:null)"
      [checked]="formdata.value.vehicles==2" >2 Wheelers</mat-checkbox>
      <mat-checkbox 
      [checked]="formdata.value.vehicles==4"
      (change)="formdata.get('vehicles').setValue($event.checked?4:null)"

      >4 Wheelers</mat-checkbox>
   </mat-radio-group>
</form>

请参见stackblitz

更新,我真的不明白这个问题,这个问题是创建一系列复选框并返回一个数组。想法是一样的,我们有一个数组(在这种情况下为对象)和一个FormControl。我们可以使用自己的对象数组

所以

<form [formGroup]="formdata">
   <label>Vehicles</label><br>
   <mat-radio-group>
      <mat-checkbox *ngFor="let v of Vehicles" 
         [checked]="v.active" 
         (change)="v.active=$event.checked;setVehicles()">
          {{ v.option }}
       </mat-checkbox>
   </mat-radio-group>
</form>

函数“ setVehicles”是为表单赋值的函数。怎么样?过滤车辆数组并映射到值

setVehicles()
  {
    this.formdata.get('vehicles').setValue(
       this.Vehicles.filter(x=>x.active) //first filter
       .map(x=>x.value)  //second map to get only the "value"
    )
  }

请参见new stackblitz

注意:我使用相同的对象数组,并在运行中添加一个属性“ active”(这是因为我将数组定义为:any [])

注意2:在这种情况下,每次您更改任何复选框时,我都会为formControl赋值,该操作仅在我们提交表单时才能使用