首页 > 解决方案 > 当对象存在于另一个数组中时如何在角度材料表中标记为选定行

问题描述

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

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

组件.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>

标签: htmlangulartypescriptangular-material

解决方案


经过一些更多的研究后,我将 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);
  }
}

原来我传递了错误数组的错误对象。


推荐阅读