单击按钮选择所有行

时间:2020-01-24 15:05:01

标签: angular primeng-datatable

我有一张餐桌。单击按钮时,希望所有行都被选中。

html:

<p-table [columns]="columns" [value]="values"
         selectionMode="multiple" [(selection)]="selectedValues"
         (onRowSelect)=selectRow(selectedValues)
         (onRowUnselect)="unselectRow($event)" #table>
  <ng-template pTemplate="header" let-columns>
    <tr>
      <th *ngFor="let col of columns">
        {{col.header}}
      </th>
    </tr>
  </ng-template>
  <ng-template pTemplate="body" let-val>
    <tr [pSelectableRow]="val">
      <td *ngFor="let col of columns">
        {{val[col.field]}}
      </td>
    </tr>
  </ng-template>
</p-table>

<div class="table-button">
  <p-button (onClick)="selectAll()">Select All</p-button>
  <p-button>Remove</p-button>
</div>

打字稿:

import {Component, OnInit, ViewChild} from '@angular/core';
import {Model} from "../../models/model.model";

@Component({
  selector: 'app-comp',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnInit {
  @ViewChild('table', {static: false}) table;

  //left out for now
  //values: Model[];

  columns: any[];

  selectedValues: Model[] = [];

  constructor() { }

  ngOnInit() {
    this.columns = [
      { field: 'Id', header: 'ID' },
      { field: 'startTime', header: 'Start Time' },
      { field: 'endTime', header: 'End Time' },
      { field: 'description', header: 'Description' },
      { field: 'insertUser', header: 'Create User' },
      { field: 'insertTime', header: 'Create Eastern Time' },
    ]
  }

  selectRow(event){
    console.log("selected row!");
  }

  unselectRow(event){
    console.log("unselected a row!")
  }

  selectAll(){
    console.log("select all is clicked");
    for (var i = 0; i < this.values.length; i++){
      this.selectedValues[i] = this.values[i];
    }
    console.log(this.table);
  }

}

当我单击按钮并检查控制台以查看它的_selection值时,可以看到整个表都已选中。这是因为我有for循环,将数据数组添加到表选择数组中。完成此操作后,如果我单击任何行,则被单击的行将显示为未单击(未突出显示),而所有其他行将被显示为已单击(突出显示)。因此,从该行为来看,除了突出显示之外,我选择所有行的方法似乎都在起作用。

所以我的问题是:

有没有更好的方法,而不是“笨拙”的方法来选择所有行并显示它们已被选中(突出显示),而不是使用for循环将它们添加到我的选择数组中?

如果此方法是选择所有行的最合逻辑的方法,那么当我单击按钮时如何将所有行表示为选中(突出显示)?

1 个答案:

答案 0 :(得分:1)

primeng表检查行Item是否在列表中(selectedValues),并且其基础将添加该类以突出显示所选行,只需按照以下this.selectedValues = [...this.values];设置列表中的数据项即可。将会完成这项工作,如果您使用复选框来选择行,则可以使用此组件<p-tableHeaderCheckbox></p-tableHeaderCheckbox>,但它的逻辑相同

`

  selectAll(){
    this.selectedValues = [...this.dataSet];
  }

demo ?