【发布时间】: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