在带有角度材料的表格列标题上显示复选框



我尝试使用来自后端的数据在表头列上制作一些复选框。

因此,如果将鼠标悬停在表标题上,则会看到标题列标题下的复选框。

我只找到了行列的解决方案,但没有找到标题列的解决方案。

所以我尝试这样做:

<ng-container matColumnDef="projects">
<th mat-header-cell *matHeaderCellDef mat-sort-header i18n>
Projects
<mat-checkbox
[style.opacity]="row.show || selection.isSelected(row) ? 100 : 0"
(click)="$event.stopPropagation()"
(change)="$event ? selection.toggle(row) : null"
[checked]="selection.isSelected(row)"
>
</mat-checkbox>
</th>
<td mat-cell *matCellDef="let row">{{row.projects}}</td>
</ng-container>

和 CSS:

.mat-header-cell mat-checkbox {
display: none;
}
.mat-header-cell:hover mat-checkbox {
display: block;
}

和组件代码:

export class ListComponent {
datasource = new MatTableDataSource<ParticipantInfoDTO>(this.participantInfo);

addShowCheckboxProperty() {
this.participantInfo.map((data: any) => {
data.show = false
});
}
handleMouseOver(column) {
const position = column.position;
this.participantInfo.map((data: any) => {
if (data.position === position) {
data.show = true;
}
});
}
handleMouseLeave(column) {
const position = column.position;
this.participantInfo.map((data: any) => {
if (data.position === position) {
data.show = false;
}
});
}
// ...
}

但是我得到一些这样的错误:

ListComponent.html:82 ERROR TypeError: Cannot read property 'show' of undefined
at Object.eval [as updateRenderer] (ListComponent.html:4)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:20458)

我不确定如何解决此问题。

为什么不简单地使用辅助数组:selection:bool[]=[]和变量show

您的列变得像

<th mat-header-cell *matHeaderCellDef 
(mouseover)="show=true" 
(mouseout)="show=false"><mat-checkbox
[style.opacity]="show ? 1 : 0"
(click)="$event.stopPropagation()"
(change)="selection[0]=$event.isChecked" //or selection[1], or selection[2]..
[checked]="selection[0]" //or selection[1], or selection[2]..
></mat-checkbox>No</th>

查看堆栈闪电战

最新更新