首页 > 代码库 > angular2.x 多选框事件

angular2.x 多选框事件

angular2.x - 4.x  的多选框事件

ng2 -- ng4 反正都是用es6 都统称为2.x吧。

下面贴代码

 

html界面

<table>
            <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>

 

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>;
      constructor() { 
      this.itemList = [1,2,3,4];
      this.selected = [];
      }
    ngOnInit() {}
      //   点击时执行
    clickItem(e,item) {
      var checkbox = e.target;
      var action = (checkbox.checked ? ‘add‘ : ‘remove‘);
      this.updateSelected(action, item);
    }
    // 用来判断input 的checked
    isCheck(item) {
      return this.selected.findIndex(value =http://www.mamicode.com/> value == item) > 0;
    }
    //  执行增加、删除
    private updateSelected(action, item) {
            console.log(‘判断‘+action);
            console.log(‘判断item=‘+item);
          if (action == ‘add‘ && this.selected.findIndex(value =http://www.mamicode.com/> value == item) == -1){
            console.log(‘执行添加‘)
            this.selected.push(item);
          }
          if (action == ‘remove‘ && this.selected.findIndex(value =http://www.mamicode.com/> value == item) != -1){
            console.log(‘执行删除‘);
            this.selected.splice(this.selected.findIndex(value =http://www.mamicode.com/> value == item), 1);
          }
      console.log(this.selected)
    }
}

界面效果

 

添加

技术分享技术分享

删除

技术分享

 

 最近才刚刚开始接触ng2 ,每天进步一点点,总有一天我也会很6的。

 

angular2.x 多选框事件