我正在使用Angular 7和Material 2,我有一个mat-table
,其中有几列,而在表格下方,我有一个mat-slide-toggle
。
当mat-slide-toggle
变成checked
时,我想用精确的字符串匹配过滤器(“活动”)过滤一列(状态)。然后,当mat-slide-toggle
为unchecked
时,我想从该列中删除该过滤器并正常显示。
我看过类似custom filter in mat-table的示例,其中设置了自定义this.dataSource.filterPredicate
,我可以这样做,但是我有些困惑:
mat-slide-toggle
时,请删除过滤器。我认为第二点需要将this.dataSource.filterPredicate
重设为默认值,但是我不确定执行此操作的代码。
这是我的代码示例,其中删除了不必要的部分以使它们正确。 status属性只有两个值“有效”和“无效”,我只想过滤“有效”用户。
example.component.ts
export class UserComponent implements OnInit {
users: User[] = [];
displayedColumns: string[] = ['name', 'status'];
dataSource = new MatTableDataSource(this.users);
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(private usersService: UsersService) { }
ngOnInit() {
this.getUsers();
this.dataSource = new MatTableDataSource(this.users);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
activeUserToggle(changeEvent: MatSlideToggleChange) {
if (changeEvent.checked) {
this.dataSource.filterPredicate =
(user: User, filter: string) => user.status.indexOf(filter) != -1;
} else {
}
}
applyFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
}
example.component.html
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> <b>Name</b> </th>
<td mat-cell *matCellDef="let row"> {{row.name}} </td>
</ng-container>
<ng-container matColumnDef="status">
<th mat-header-cell *matHeaderCellDef mat-sort-header> <b>Status</b> </th>
<td mat-cell *matCellDef="let row"> {{row.status}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row;
let even = even;
columns: displayedColumns;" [ngClass]="{grey: even}">
</tr>
</table>
<mat-paginator [pageSizeOptions]="[10, 25, 100]"></mat-paginator>
</div>
<mat-slide-toggle class="activeUserSlide" (change)="activeUserToggle($event)">Show only active users</mat-slide-toggle>
答案 0 :(得分:1)
您可以在未选中的情况下将值重置回此用户。
activeUserToggle(changeEvent: MatSlideToggleChange) {
if (changeEvent.checked) {
this.dataSource.filterPredicate =
(user: User, filter: string) => user.status.indexOf(filter) != -1;
} else {
this.dataSource.data = this.users;
}
}