如何使用multiTemplateDataRows和paginator在mat表中查找行索引



我想要行索引,这样我就可以在控件的ngModel中使用它

我的表格:(在添加分页功能之前(

<mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8">
....
<td mat-cell *matCellDef="let element; let rowIdx = dataIndex;">
...
<mat-select disableRipple class="go" [(ngModel)]="schedule.todo[rowIdx].notes"
name="some{{element}}">

以及更多使用rowIdx 的列

我的分页正在中工作

<mat-paginator[pageSizeOptions]=";[5;显示第一个最后一个按钮aria标签=";每页选择项目">

问题无法计算正确的索引,因为第2页再次以0开头。

有可能修复这条线上的一些东西吗

*<td mat-cellmatCellDef=";let元素;let rowIdx=dataIndex"gt

并具有可重复使用的行索引?

请澄清,您试图获得什么行索引?如果您在5处有分页器,并且您在第1页上,则会出现1-5行的行id。为此,我实现了一种方法,使用paginator来计算我们所处的索引,并使用onContentChange来检测页面移动时的更改。

<!-- ID Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
<td mat-cell *matCellDef="let row; let innerIndex = index" #something (click)="onClickItemId(row.id);onClickRowEvent(innerIndex)" style="background: green"> {{row.id}} </td>
</ng-container>
@Component({
selector: 'table-overview-example',
styleUrls: ['table-overview-example.css'],
templateUrl: 'table-overview-example.html',
})
export class TableOverviewExample implements AfterViewInit {
displayedColumns: string[] = ['id', 'name', 'progress', 'fruit'];
dataSource: MatTableDataSource<UserData>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
startingIndexOfPage: number;
endingIndexOfPage: number
clickedItemId: number;
count: number;
innerIndexCalculated: number;
constructor() {
// Create 100 users
const users = Array.from({length: 100}, (_, k) => createNewUser(k + 1));
// Assign the data to the data source for the table to render
this.dataSource = new MatTableDataSource(users);
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
onContentChange(event: any) {
this.getCurrentIndex()
}
getCurrentIndex() {
this.startingIndexOfPage = this.paginator.pageIndex * this.paginator.pageSize;
this.endingIndexOfPage = (this.paginator.pageIndex * this.paginator.pageSize) + this.paginator.pageSize;
}
onClickItemId(itemId: number) {
this.clickedItemId = itemId;
}
onClickRowEvent(innerIndex: number) {
this.innerIndexCalculated = this.startingIndexOfPage + innerIndex + 1;
}
}
startingIndexOfPage: {{startingIndexOfPage}}
<br>
endingIndexOfPage: {{endingIndexOfPage}}
<br>
clickedItemId: {{clickedItemId}}
<br>
innerIndexCalculated: {{innerIndexCalculated}}

以下是一个工作示例:https://stackblitz.com/edit/angular-tbwai9-wax11m?file=src%2Fapp%2Ftable-overview-example.html

最新更新