如何解决如果在 *ngIf
我正在使用带有分页器的垫子表并在 *ngIf
内排序。使用 API 检索表数据。
这是组件的打字稿代码:
export class UserPermissionAdminComponent implements AfterViewInit,OnInit {
dataSource: MatTableDataSource<UserPermission> = new MatTableDataSource<UserPermission>();
columnsTodisplay: string[] = ['id','name'];
@ViewChild(MatSort,{ static: false }) sort!: MatSort;
@ViewChild(MatPaginator,{ static: false }) paginator!: MatPaginator;
constructor(private userPermService: UserPermissionService) {
}
ngOnInit(): void {
this.userPermService.getAllUserPermissions()
.subscribe(recvPerms => this.dataSource.data = recvPerms);
}
ngAfterViewInit(): void {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
console.log(this.dataSource.sort);
}
applyFilter(event: Event): void {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}
}
这是组件的模板:
<div class="container">
<h2>Permisiuni utilizatori</h2>
<ng-container *ngIf="dataSource.data.length; then existingPermissions; else nopermissions">
</ng-container>
<ng-template #existingPermissions>
<div>
<div class="filter-container">
<mat-form-field>
<mat-label>Cautare</mat-label>
<input matInput (keyup)="applyFilter($event)" placeholder="Ex: READ" #input />
</mat-form-field>
</div>
<div class="table-container mat-elevation-z8">
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
<td mat-cell *matCellDef="let permission"> {{permission.id}} </td>
</ng-container>
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Denumire permisiune </th>
<td mat-cell *matCellDef="let permission"> {{permission.name}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsTodisplay"></tr>
<tr mat-row *matRowDef="let rowData; columns: columnsTodisplay"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5,10,20]"></mat-paginator>
</div>
</div>
</ng-template>
<ng-template #nopermissions>
<div>
<span class="notification">Nu a fost gasita nicio permisiune utilizator.</span>
</div>
</ng-template>
</div>
问题是排序和分页不起作用(console.log 还列出了 this.sort
是 undefined
)。该表包含单个页面上的所有数据。过滤也有效。
解决方法
我已通过向分页器添加 setter 并排序来解决此问题:
@ViewChild(MatSort,{ static: false }) set sort(val: MatSort) {
if (val) {
this.dataSource.sort = val;
}
}
@ViewChild(MatPaginator,{ static: false }) set paginator(val: MatPaginator) {
if (val) {
this.dataSource.paginator = val;
}
}
然而,即使没有 ngAfterViewInit
,代码现在也能工作。有人可以解释一下这是如何以及为什么起作用的吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。