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

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

问题描述

我正在使用Angular中的复选框选择多个数据,并试图获取表单提交中复选框的值,而不是将值im作为真实值获取.我尝试了以下代码来帮助我谢谢前进

I m using checkbox in angular to select more than one data and im trying to get the value of check box on the form submit.Instead getting the value im getting value as true.I have tried the following code help me thanks in advance

   export class CreatesessionComponent implements OnInit {    
      form : FormGroup ;
      constructor(private formBuilder: FormBuilder) {       
      }        
      ngOnInit() {
       this.form = this.formBuilder.group({     
          useremail :  new FormArray([
            new FormControl('',Validators.required)
          ])    
      });
    }
  }

userdata是动态数组,我将从数据库中获取

userdata is dynamic array which i will get the from the database

<div class = "row" formArrayName="useremail; let k = index">
   <div class="col-md-8 col-sm-5 col-xs-12 col-lg-8">
       <div *ngFor="let data of userdata">
           <div class="col-md-6">
               <input type="checkbox" name="useremail" formControlName ="{{k}}" [value]="data.email">{{data.email}}
           </div>
       </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,在其中检查是否为checked,然后将相应的电子邮件添加到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);
  }
}

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

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