【发布时间】:2020-07-10 15:31:52
【问题描述】:
我有以下代码,其中包含多选列的材料表。我注意到的是,每次鼠标移动 isAllSelected() 都会被调用数百次。为什么会这样。我认为只有在单击复选框时才应该调用它
<mat-table #table [dataSource]="dataSource">
<!-- Checkbox Column -->
<ng-container matColumnDef="checkbox">
<mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()">
</mat-checkbox>
</mat-header-cell>
<mat-cell *matCellDef="let priority">
<mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(priority) : null"
[checked]="selection.isSelected(priority)">
</mat-checkbox>
</mat-cell>
</ng-container>
<!-- Colour Column -->
<ng-container matColumnDef="colour">
<mat-header-cell *matHeaderCellDef>Colour</mat-header-cell>
<mat-cell *matCellDef="let priority">{{priority?.colour}}</mat-cell>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let priority">{{priority?.name}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let priority; columns: displayedColumns;" class="contact" (click)="selection.toggle(row)">
</mat-row>
</mat-table>
和 .ts 文件
export class AdminPrioritiesSettingsComponent {
dataSource: MatTableDataSource<any>;
selection = new SelectionModel<PriorityDto>(true, []);
displayedColumns = ['checkbox', 'colour', 'name'];
isAllSelected() {
console.log(this.selection.hasValue());
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
/** Selects all rows if they are not all selected; otherwise clear selection. */
masterToggle() {
this.isAllSelected() ?
this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row));
}
}
【问题讨论】:
-
不确定是否相关,但
(change)="$event ?应替换为(change)="$event.checked ?。布尔状态包含在事件对象的checked属性中。 -
@ShubhamBhokare 我从官方角度材料示例中得到了这个例子
-
@pantonis:你能链接那个例子吗?
-
浏览我上面分享的中篇文章。它有 2 种策略,任何一种都可以在您的代码中使用。
标签: angular typescript angular-material angular8