1. 程式人生 > >angular4實現購物車全選、反選、單選功能

angular4實現購物車全選、反選、單選功能

 

    <div class="items" *ngFor="let item of data; let i = index;">
      <input type="checkbox" name="checkSingle[]" class="my_checkbox singleCheck"         
     (click)="checkSingle()">   
    </div>


    <input type="checkbox" name="checkAll" class="my_checkbox" id="allCheck" 
      (click)="checkAll()">
    <label for="allCheck">全選</label>
  // 全選
  checkAll () {
    const all = document.getElementById('allCheck');
    const singles = document.getElementsByClassName('singleCheck');
    for (let i = 0; i < singles.length; i++) {
      if (all['checked']) {
        const single = singles[i];
        single['checked'] = true;
      }
    }
    for (let i = 0; i < singles.length; i++) {
      if (!all['checked']) {
        const single = singles[i];
        single['checked'] = false;
      }
    }
  }

  // 單選
  checkSingle () {
    const all = document.getElementById('allCheck');
    const singles = document.getElementsByClassName('singleCheck');
    let count = 0;
    for (let i = 0; i < singles.length; i++) {
      const single = singles[i];
      if (single['checked']) {
        count++;
      } else {
        count = count;
      }
    }
    if (count === singles.length) {
      all['checked'] = true;
    } else {
      all['checked'] = false;
    }
  }