angular2.x - 4.x 的多選框事件
ng2 -- ng4 反正都是用es6 都統稱為2.x吧。
下面貼代碼
html界面
<div class="row"> <div class="col-md-9"> <table> <thead> <tr> <th><input type="checkbox" (click)="selectAll($event)" [checked]="isSelectedAll()" />全選</th> </tr> </thead> <tbody> <tr *ngFor="let item of itemList"> <td> <input type="checkbox" [checked]="isCheck(item)" (click)="clickItem($event,item)" /> </td> <td>{{ item }}</td> </tr> </tbody> </table> </div> </div>
ts代碼:
import { Component, OnInit } from '@angular/core'; import { RankingService } from '../ranking/services/ranking.service'; @Component({ selector: 'app-classify', templateUrl: './classify.component.html', styleUrls: ['./classify.component.css'] }) export class ClassifyComponent implements OnInit { public itemList: Array<any>; public selected: Array<any>; public allList: Array<any>; public idListAll: Array<any>; constructor() { this.itemList = [1, 2, 3, 4]; this.allList = [1, 2, 3, 4]; this.idListAll = [1, 2, 3, 4]; this.selected = []; } ngOnInit() {} // 點擊時執行 clickItem(e, item) { const checkbox = e.target; const action = (checkbox.checked ? 'add' : 'remove'); this.updateSelected(action, item); } // 用來判斷input 的checked isCheck(item) { return this.selected.findIndex(value => value == item) >= 0; } // 執行增加、刪除 private updateSelected(action, item) { if (action == 'add' && this.selected.findIndex(value => value == item) == -1){ console.log('執行添加'); this.selected.push(item); } if (action == 'remove' && this.selected.findIndex(value => value == item) != -1){ console.log('執行刪除'); this.selected.splice(this.selected.findIndex(value => value == item), 1); } console.log(this.selected); } // 全選點擊事件 selectAll(e) { const checkbox = e.target; const action = (checkbox.checked ? 'add' : 'remove'); this.allList.forEach((elt, i, array) => { const entity = elt; this.updateSelected(action, entity); }); } // 判斷是否全選 isSelectedAll() { return this.isContained(this.selected, this.idListAll); } // 判斷b數組是否包含在a數組中 private isContained(a, b) { if (!(a instanceof Array) || !(b instanceof Array)) return false; if (a.length < b.length) return false; const aStr = a.toString(); for (let i = 0, len = b.length; i < len; i++) { if (aStr.indexOf(b[i]) == -1) { return false; } } return true; } }
界面效果
全選
添加
刪除
最近才剛剛開始接觸ng2 ,每天進步一點點,總有一天我也會很6的。