Angular如何获取多个复选框值? [英] Angular how to get the multiple checkbox values?

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

问题描述

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

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.

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

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 是从数据库填充的动态数组.

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> 

推荐答案

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

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

首先声明一个空的formArray:

Start with declaring an empty formArray:

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

遍历您的电子邮件,并查看更改事件,并将相应的电子邮件和事件传递给方法 onChange ,在其中检查是否已被选中,然后分别添加电子邮件发送到formarray,如果未选中,请从表单数组中删除所选电子邮件:

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>

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆