首页 > 解决方案 > Angular Material - 在数据源更改时保留原始复选框选择

问题描述

在 mat-table 中,当数据源发生更改,然后又恢复回来时,我希望再次选中最初选中的复选框。假设我选择了 1 号和 2 号复选框。然后更改数据源。然后它恢复到以前的状态。在这种情况下,我希望自动选中之前选择的复选框 1 和 2。选择包含这些记录,但不会检查它们。

我有一个mat-table复选框列:

<ng-container matColumnDef="selectColumn">
    <mat-header-cell *matHeaderCellDef></mat-header-cell>
    <mat-cell *matCellDef="let element">
    <input id="checkBox" type="checkbox" (change)="$event ? selection.toggle(element) : null; updateSelection();"
        [checked]="selection.isSelected(element)" (click)="$event.stopPropagation();">
    </mat-cell>
</ng-container>

TS:

selection = new SelectionModel(true, AppConstants.selectedRecords);

updateSelection() {
    console.log(this.selection.selected);
}

createRecordingsTable() {
    // ... logic to update this.records
    this.dataSource = new MatTableDataSource(this.records);
    console.log(this.selection.selected);
}

现在,当数据源恢复为原始数据源时,不会选中复选框 1 和 2,即使选择中有它们的条目。此外,如果我再次单击 1 和 2,将在选择中创建重复条目。

我该如何解决这个问题?

标签: angulartypescriptangular-material

解决方案


推荐阅读