如何获取多个复选框值

如何获取多个复选框值

本文介绍了Angular 如何获取多个复选框值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 中使用一个复选框来选择多个元素,我正在尝试获取该复选框的值以进行提交.

相反,我将这些值作为 true-s 数组获取.这就是我尝试过的:

导出类 CreateSessionComponent 实现 OnInit {表单:表单组;构造函数(私有 formBuilder:FormBuilder){}ngOnInit() {this.form = this.formBuilder.group({用户数据:新的 FormArray([new FormControl('', Validators.required)])})}}

userdata 是从数据库填充的动态数组.

<div formArrayName="useremail;令k=索引"><div *ngFor=让用户数据的数据"><div>{{data.email}}

解决方案

由于您有多个要使用的值,因此您需要使用 FormArray,因为 FormControl只能捕获一个值.

从声明一个空的 formArray 开始:

this.myForm = this.fb.group({用户邮箱:this.fb.array([])});

迭代您的电子邮件,并观察更改事件并将相应的电子邮件和事件传递给方法 onChange,您可以在其中检查它是否被 checked,然后添加相应的将电子邮件发送到表单数组,如果未选中,则从表单数组中删除所选电子邮件:

<input type="checkbox" (change)="onChange(data.email, $event.target.checked)">{{data.email}}

onChange:

onChange(email:string, isChecked: boolean) {const emailFormArray = <FormArray>this.myForm.controls.useremail;如果(已检查){emailFormArray.push(new FormControl(email));} 别的 {让 index = emailFormArray.controls.findIndex(x => x.value == email)emailFormArray.removeAt(index);}}

演示

I m using a checkbox in Angular to select more than one element and I'm trying to get the value of that checkbox for submitting.

Instead I'm getting the value those values as an array of true-s.That's what I've tried:

export class CreateSessionComponent implements OnInit {
  form : FormGroup ;

  constructor(private formBuilder: FormBuilder) {}

  ngOnInit() {
    this.form = this.formBuilder.group({
      userdata :  new FormArray([
        new FormControl('', Validators.required)
      ])
    })
  }
}

userdata is a dynamic array populated from a database.

<div formArrayName="useremail; let k = index">
  <div *ngFor="let data of userdata">
    <div>
      <input type="checkbox" name="useremail" formControlName ="{{k}}" [value]="data.email">{{data.email}}
    </div>
  </div>
</div>
解决方案

Since you have several values you want to use, you need to use an FormArray, since FormControl can only capture one value.

Start with declaring an empty formArray:

this.myForm = this.fb.group({
  useremail: this.fb.array([])
});

Iterate the your emails, and watch for the change event and pass the respective email and event to a method onChange where you check if it's checked, then add the respective email to the formarray, if it's unchecked, remove the chosen email from the form array:

<div *ngFor="let data of emails">
  <input type="checkbox" (change)="onChange(data.email, $event.target.checked)"> {{data.email}}<br>
</div>

And onChange:

onChange(email:string, isChecked: boolean) {
  const emailFormArray = <FormArray>this.myForm.controls.useremail;

  if(isChecked) {
    emailFormArray.push(new FormControl(email));
  } else {
    let index = emailFormArray.controls.findIndex(x => x.value == email)
    emailFormArray.removeAt(index);
  }
}

Demo

这篇关于Angular 如何获取多个复选框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 13:46