从按钮点击的多个复选框中选择值?

时间:2018-05-02 08:00:30

标签: angular ionic-framework

<td><p><input  class="checkbox"  type="checkbox" value="Cars.id"> </p> </td>

这是带有复选框的汽车ID列表。

 <button (click)="duplicate()"><ion-icon name="color-wand"></ion-icon> </button> 

在此按钮上单击我想获取我的.ts文件中所有汽车的值。这是.ts中的函数

duplicate() {
    var checkedValue = document.querySelector('.messageCheckbox:checked');
}

1 个答案:

答案 0 :(得分:1)

为了获取复选框的所有值,Angular中有几种方法可用。在这个答案中,我将告诉你不使用任何formArray。像这样 -

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

<button (click)="duplicate()" >Get values </button> 
 ----------------------------
emailFormArray: Array<any> = [];
  Cars = [ 
    {email:"email1", id: 1},
    {email:"email2", id: 2},
    {email:"email3", id: 3},
    {email:"email4", id: 4}
  ];

  onChange(email:string, isChecked: boolean) {
      if(isChecked) {
        this.emailFormArray.push(email);
      } else {
        let index = this.emailFormArray.indexOf(email);
        this.emailFormArray.splice(index,1);
      }
  }

  duplicate() {
    console.log(this.emailFormArray);
  }

Working Example