【问题标题】:Whole row of checkboxes being selected整行复选框被选中
【发布时间】:2023-03-04 17:01:01
【问题描述】:

我正在使用 Mat 表的示例添加另一个带有复选框的列。但是,当我单击一列时,其他列复选框也会被选中。如何正确实现它,以便仅选中特定列的复选框并跟踪它。 https://stackblitz.com/edit/angular-aouc8q

【问题讨论】:

    标签: angular checkbox mat-table


    【解决方案1】:

    我已经更新了代码。用您的代码替换此代码。

    您需要为第二个复选框列使用单独的SelectionModel

    table-selection-example.html

    <table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
    
      <!-- Checkbox Column -->
      <ng-container matColumnDef="select">
        <th mat-header-cell *matHeaderCellDef>
          <mat-checkbox (change)="$event ? masterToggle('one') : null"
                        [checked]="selection.hasValue() && isAllSelected()"
                        [indeterminate]="selection.hasValue() && !isAllSelected()"
                        [aria-label]="checkboxLabel('one')">
          </mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let row">
          <mat-checkbox (click)="$event.stopPropagation()"
                        (change)="$event ? selection.toggle(row) : null"
                        [checked]="selection.isSelected(row)"
                        [aria-label]="checkboxLabel(row, 'one')">
          </mat-checkbox>
        </td>
      </ng-container>
    
      <!-- Position Column -->
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef>
          <mat-checkbox (change)="$event ? masterToggle('two') : null"
                        [checked]="position.hasValue() && isAllSelected()"
                        [indeterminate]="position.hasValue() && !isAllSelected()"
                        [aria-label]="checkboxLabel('two')">
          </mat-checkbox>
        </th>
        <td mat-cell *matCellDef="let row">
          <mat-checkbox (click)="$event.stopPropagation()"
                        (change)="$event ? position.toggle(row) : null"
                        [checked]="position.isSelected(row)"
                        [aria-label]="checkboxLabel(row, 'two')">
          </mat-checkbox>
        </td>
      </ng-container>
      <!-- Name Column -->
      <ng-container matColumnDef="name">
        <th mat-header-cell *matHeaderCellDef> Name </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>
    
      <!-- Weight Column -->
      <ng-container matColumnDef="weight">
        <th mat-header-cell *matHeaderCellDef> Weight </th>
        <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
      </ng-container>
    
      <!-- Symbol Column -->
      <ng-container matColumnDef="symbol">
        <th mat-header-cell *matHeaderCellDef> Symbol </th>
        <td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
      </ng-container>
    
      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"
          (click)="selection.toggle(row)">
      </tr>
    </table>
    
    
    <!-- Copyright 2019 Google Inc. All Rights Reserved.
        Use of this source code is governed by an MIT-style license that
        can be found in the LICENSE file at http://angular.io/license -->
    

    table-selection-example.ts

    import {SelectionModel} from '@angular/cdk/collections';
    import {Component} from '@angular/core';
    import {MatTableDataSource} from '@angular/material';
    
    export interface PeriodicElement {
      name: string;
      position: number;
      weight: number;
      symbol: string;
    }
    
    const ELEMENT_DATA: PeriodicElement[] = [
      {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
      {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
      {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
      {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
      {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
      {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
      {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
      {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
      {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
      {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
    ];
    
    /**
     * @title Table with selection
     */
    @Component({
      selector: 'table-selection-example',
      styleUrls: ['table-selection-example.css'],
      templateUrl: 'table-selection-example.html',
    })
    export class TableSelectionExample {
      displayedColumns: string[] = ['select', 'position', 'name', 'weight', 'symbol'];
      dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
      selection = new SelectionModel<PeriodicElement>(true, []);
      position = new SelectionModel<PeriodicElement>(true, []);
    
      /** Whether the number of selected elements matches the total number of rows. */
      isAllSelected(which) {
        if (which == "one"){
          const numSelected = this.selection.selected.length;
          const numRows = this.dataSource.data.length;
          return numSelected === numRows;
        } else if(which == "two"){
          const numPosition = this.position.selected.length;
          const numRows = this.dataSource.data.length;
          return numPosition === numRows;
        }
    
      }
    
      /** Selects all rows if they are not all selected; otherwise clear selection. */
      masterToggle(which) {
        if (which == "one"){
          this.isAllSelected(which) ?
            this.selection.clear() :
            this.dataSource.data.forEach(row => this.selection.select(row));
        } else if(which == "two"){
          this.isAllSelected(which) ?
            this.position.clear() :
            this.dataSource.data.forEach(row => this.position.select(row));
        }
    
      }
    
      /** The label for the checkbox on the passed row */
      checkboxLabel(row?: PeriodicElement, which = "one"): string {
        if (!row) {
          return `${this.isAllSelected(which) ? 'select' : 'deselect'} all`;
        }
        return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.position + 1}`;
      }
    }
    
    
    /**  Copyright 2019 Google Inc. All Rights Reserved.
        Use of this source code is governed by an MIT-style license that
        can be found in the LICENSE file at http://angular.io/license */
    

    希望这个解决方案对你有用。

    【讨论】:

    • 感谢这成功了!有没有更好的解决方案,因为我实际上要使用大约四列
    • @Flash 将更新完整代码并在 stackblitz.com 中分享,谢谢。
    • 非常感谢
    • 还有你将如何跟踪哪些被选中,哪些未被选中
    猜你喜欢
    • 1970-01-01
    • 2017-06-07
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多