美文网首页
Angular6+NG-ZORRO 表格单选设置

Angular6+NG-ZORRO 表格单选设置

作者: 躺赢lu | 来源:发表于2019-05-09 15:20 被阅读0次

    就是辣种单选表格内容,每次被勾选的只能有一个,勾选了另一个前一个自动取消,结合文档里面的一些内置属性和方法可以实现。

    首先是在td上绑nzCheckedChange函数,这里tr增加了一个click函数,用于当前被点击的那条数据的checked切换:

    <tr *ngFor="let data of dataSet.data"  (click)="trEvent(data)">
      <td nzShowCheckbox [(nzChecked)]="data.checked" (nzCheckedChange)="chooseItem($event, data)">
      ...
    </td>
    </tr>
    

    然后是ts代码:
    this.filterChecked代表所勾选的数据,是一个数组形式的,eventdata.checked值,item是被选中的数据

    chooseItem (event, item, array = this.filterChecked) {
        item.checked = event;       // 更改data.checked值
        let currentIndex;
        if (event){                          // 如果被选中
          if(JSON.stringify(array).indexOf(JSON.stringify(item)) === -1) {                // 去重
            array.push(item);
          }
          this.refreshStatus();
        } else if (!event) {
          array.forEach( (value, index) => {
            if ( value.name === item.name ) {
              currentIndex = index;
            }
          })
          array.splice(currentIndex, 1);
            this.refreshStatus();
        }
      }
    

    this.refreshStatus()函数主要是看数据是否被全选,如果是手动选择了全部的数据,通过这个函数可以点亮表头里的allCheck勾选框(这里没有,可以忽略):

      refreshStatus() {
        const allChecked = this.currentPageData.filter(value => !value.disabled).every(value => value.checked === true);
        if (this.currentPageData.length > 0) {
          this.allChecked = allChecked;
        } else if (this.currentPageData.length === 0) {
          this.allCheckedPatch = false;
        }
      }
    

    这里我试了很多次,在chooseItem()函数里把其他data.checkedfalse或者是把this.filterChecked置为空啊,都不行。然后轮到trEvent()函数出场辽:

     trEvent(data){
        this.filterChecked = [];     // 先把选中的数据清空
        data.checked = !data.checked;     // 更改当前数据的checked状态
        this.currentPageData.forEach(v => {   // this.currentPageData就是文档里的当前页数据
          if (v !== data) {   // 把不是当前选中数据的checked都改成false
            v.checked = false;
          }
        });
      this.chooseItem(data.checked, data);         // 进入这个函数更新this.filterChecked
    

    相关文章

      网友评论

          本文标题:Angular6+NG-ZORRO 表格单选设置

          本文链接:https://www.haomeiwen.com/subject/nlvwoqtx.html