当对象存在于另一个数组中时,如何在角度材料表中标记为选定行



我想将表的行标记为选中,如果它们位于与表数据源不同的数组中。

这是我到目前为止所做的:

组件.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,它也取自 Angular Material 文档:

<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);
}
}

事实证明,我传递了错误数组的错误对象。

最新更新