html - 当对象存在于另一个数组中时如何在角度材料表中标记为选定行
问题描述
如果表格的行与表格数据源位于不同的数组中,我想将它们标记为选中。
这是我到目前为止所做的:
组件.ts
dataSource = new MatTableDataSource<MyModel>([]);
selection = new SelectionModel<MyModel>(true, []);
arrayToCompareWith: AnotherModel[];
//The part use for selection in UI copy from Angular Material Docs
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.resultsDs.data.length;
return numSelected === numRows;
}
masterToggle() {
this.isAllSelected() ?
this.selection.clear() :
this.resultsDs.data.forEach(row => this.selection.select(row));
}
checkboxLabel(row?: SdsSectionModel): string {
if (!row) {
return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
}
return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.sectionId + 1}`;
}
\\The method I'm trying to use to select the rows in code
addToSelectedRows(): void{
for(let option of this.arrayToCompareWith){
\\myModelProp is of type MyModel
this.selection.toggle(option.myModelProp);
}
}
这实际上选择了对象并将它们添加到选择对象,但它不会更新 UI。
这是从角度材料文档中获取的选择列的html:
<ng-container matColumnDef="select">
<th mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? masterToggle() : null"
[checked]="selection.hasValue() && isAllSelected()"
[indeterminate]="selection.hasValue() && !isAllSelected()"
[aria-label]="checkboxLabel()">
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">
<div style="width: 3px">
<mat-checkbox (click)="$event.stopPropagation()"
(change)="$event ? selection.toggle(row) : null"
[checked]="selection.isSelected(row)"
[aria-label]="checkboxLabel(row)">
</mat-checkbox>
</div>
</td>
</ng-container>
解决方案
经过一些更多的研究后,我将 addToSelected 方法更改为:
private addToSelected(): void {
for (let option of this.arrayToCompareWith) {
const exists = this.dataSource.data.filter(x => x.id === option.myModelProp.id)[0];
this.selection.toggle(exists);
}
}
原来我传递了错误数组的错误对象。
推荐阅读
- algorithm - 我知道 2 SAT 可以在多项式时间内解决,找出强连通分量。为 3SAT 做同样的事情怎么样?
- c# - 树列表。如何使扩展列右侧的列保持宽度?
- java - 使用 java nio 从 FileChannel 读取
- python - ValueError:索引 7 处不支持的格式字符“p”(0x70)
- twitter - Twitter 内部 API 中的latent_count 是做什么用的?
- c# - 检测用户何时按下红色 x
- c++ - 使用公共 PRNG 和均匀分布 (C++17)
- php - Wordpress - 激活插件后添加页面
- javascript - 'form-data/multipart' 类型的 HTTPS 请求(使用 https nodejs 模块)不起作用
- python - 从文本文件中提取某些项目以进行标记化