【问题标题】:How to programmatically set check state of mat-checkbox in mat-table?如何以编程方式设置 mat-table 中 mat-checkbox 的检查状态?
【发布时间】:2021-09-12 23:19:23
【问题描述】:

我将 Angular 与材料一起使用,具体来说,我正在使用 mat-table 构建一个表格。 我的表很简单,有两列 - 名称列和“选择”列(复选框)。

这是我的表格组件代码:

    <mat-table #table [dataSource]="dataSource" matSort matSortActive="name">
  
      <ng-container matColumnDef="name">
        <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{element.name}} </mat-cell>
      </ng-container>
  
      <ng-container matColumnDef="select">
        <mat-header-cell *matHeaderCellDef> Select </mat-header-cell>
        <mat-cell *matCellDef="let element"> 
        
          <mat-checkbox #checkBox [value]="element.position"(change)="getCheckbox(checkBox)"></mat-checkbox>
        
        </mat-cell>
      </ng-container>
  
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row (click)="setCheckedState()" *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>

然后我使用以下代码收集检查项目的列表:

  @ViewChildren ('checkBox') checkBox: QueryList<any> | undefined;

  checked: any = [];

  getCheckbox(checkbox: any){
    this.checked = []; // resetting each Time new event is fire.
    // filtering only checked vlaue and assign to checked variable.
    const checked = this.checkBox?.filter(checkbox => checkbox.checked);

    // then, we make object array of checked, and value by checked variable  
    checked?.forEach(data => {
      this.checked.push ({ 
        'checked' : data.checked,
        'value':  data.value
      });
    });
  }

Stackbliz 获取检查项目列表的示例:https://stackblitz.com/edit/angular-efyvdr?file=src%2Fapp%2Fapp.component.html

mat-table 上,我想做的是单击该行以设置该行复选框的选中状态。

我尝试了此设置单击行(确实触发),但似乎无法捕捉该行的复选框。如何根据 mat-row 点击设置选中状态(真/假)?

提前感谢您的任何指点!

【问题讨论】:

  • 试试这个。我认为最大的问题是使用[value] 而不是[(ngModel)]
  • 我还创建了一个类来存储名称和值。这样您就可以直接引用数组,而不是通过文档查询。这就是 Angular 的做事方式
  • 感谢@Chad K - 这几乎可以与mat-table 一起使用 - 请在此处查看更新的堆栈闪电:stackblitz.com/edit/angular-xmqhru?file=src/app/… - 我可以单击行进行选择。但是,直接单击复选框不起作用 - 对此有何想法?
  • 看起来你打败了我 - 在父元素上添加 (click) 处理程序会阻止复选框正常工作。该问题的另一个解决方案是在复选框元素上添加另一个 (click) 处理程序,就像在其余部分一样,再次查看堆栈溢出:stackblitz.com/edit/…

标签: angular angular-material mat-table


【解决方案1】:

最简单的方法是创建一个类来保存复选框的名称和状态,类似于:

export class ItemStatus {
  name: string;
  checked: boolean;
  id: number;

  constructor(id, name) {
    this.id = id;
    this.name = name;
    this.checked = false;
  }
}

然后,您改为使用[(ngModel)] 而不是[value],如下所示:&lt;mat-checkbox [(ngModel)]="element.checked"&gt;

最后,将 get checked 函数更改为根据已检查状态进行过滤,如下所示:

getCheckedItems() {
   this.checked = this.items.filter(i => i.checked == true);
}

总结一下,这里是一个堆栈闪电战: https://stackblitz.com/edit/angular-gg394h?file=src%2Fapp%2Fapp.component.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    • 2018-06-11
    • 2018-07-25
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多