typescript 如何对Angular材料进行分页?

c0vxltue  于 2022-12-19  发布在  TypeScript
关注(0)|答案(2)|浏览(135)

我正在按照Muhi Masri Load, Add, Update and Delete Table Rows using API Services的教程(顺便说一句,完全推荐的教程)制作一个可编辑的动态表。
使用我每次过滤日期时渲染的数据源。但是我想添加一个Angular 材质分页器,但是它不起作用。我不太明白为什么,我按照文档中提到的那样做了,但是仍然没有任何效果。
this.dataSource._filterData.length返回1

// The columns
  displayedColumns: string[] = ActivityColumns.map((col) => col.key);
   columnsSchema: any = ActivityColumns;

// The date
   dataSource = new MatTableDataSource<ApidatumDisplay>();
   request: ApidatumDisplay[] = []

getDataIsSelected() {
     let dailydata = {
       startDate: this.selected.startDate.format("YYYY-MM-DD"),
       endDate: this.selected.endDate.format("YYYY-MM-DD")
     }

     const validStartSelected = dailydata.startDate;

     const validd = (validStartSelected === dayjs().format("YYYY-MM-DD")) ? this.editDateisNow = true : this.editDateisNow = false;

    // Request get this.reportesService.getDailyTracking(dataDaily).pipe(takeUntil(this.unsubscribe$)).subscribe((res) => {
       this.request = res.apidata;
       this.dataSource.data = this.request;
       console.log('length',this.dataSource._filterData.length); // returns 1
       this.averageTotal = res.adding_total_activity
       this.hourTimeTotal = this.convert(res.adding_total_hours);
       this.expectedBudget = 192 * 22;
       this.isReload = false;
     });
   }

超文本标记语言

<!--Table of content-->
<section class="rounded mt-2 border overflow-hidden">

  <table mat-table [dataSource]="dataSource">
    <ng-container class="text-uppercase border" [matColumnDef]="col.key" *ngFor="let col of columnsSchema">
      <th class="vertical-align-middle" mat-header-cell *matHeaderCellDef>
        <div class="d-flex align-items-center">
          <div class=" text-size-4 text-overflow mr-1">
            {{ col.label }}
          </div>
        </div>
      </th>
      <td class=" text-size-3 font-weight-regular " mat-cell *matCellDef="let element">
        <div class="text-overflow text-size-4 mr-1" [ngSwitch]="col.type" *ngIf="!element.isEdit">
          <div class="btn-edit" *ngSwitchCase="'isEdit'">
            <button mat-button (click)="element.isEdit=
                    !element.isEdit">
                    Editar
                  </button>
          </div>
          <span *ngSwitchCase="'text'">
                  {{ element[col.key] }}
                </span>
          <span *ngSwitchDefault>
                  {{ element[col.key] }}
                </span>
          <div class="text-overflow text-size-4" *ngSwitchCase="'indicator_hour_daily'">
            <img style="height: 12px;" src="https://ymlabqgbnnbvyybcyqjn.supabase.co/storage/v1/object/public/assets-ui/icons/status-{{element.indicator_hour_daily}}.svg" alt="status">
          </div>
          <div class="text-overflow text-size-4" *ngSwitchCase="'indicator_activity_daily'">
            <img style="height: 12px;" src="https://ymlabqgbnnbvyybcyqjn.supabase.co/storage/v1/object/public/assets-ui/icons/status-{{element.indicator_activity_daily}}.svg" alt="status">
          </div>
        </div>
        <div class="text-overflow text-size-4" [ngSwitch]="col.type" *ngIf="element.isEdit">
          <div *ngSwitchCase="'isSelected'"></div>
          <div class="btn-edit" *ngSwitchCase="'isEdit'">
            <button mat-button (click)="editRow(element)">Hecho</button>
            <button mat-button (click)="cancelEditActivity(element)">Cancelar</button>
          </div>
          <mat-form-field *ngSwitchCase="col.type ==='activity_daily' ?
                  col.type : col.type ==='text'">
            <input matInput [type]="col.type" [(ngModel)]="element[col.key]" />
          </mat-form-field>
          <mat-form-field *ngSwitchCase="col.type ==='text' ? col.type :
                  ''">
            <input [type]="col.type" matInput [(ngModel)]="element[col.key]" disabled/>
          </mat-form-field>
          <mat-form-field class="text-overflow text-size-4
                  resizeMatSelect" *ngSwitchCase="'indicator_hour_daily'" ng-disabled="'isEdit'">
            <img with="12" height="12" [src]="selectedLanguage">
            <mat-select [(value)]="selectedLanguage">
              <mat-select-trigger>
                {{selectedLanguage}}
              </mat-select-trigger>
              <mat-option *ngFor="let category of categories" [value]="category.image">
                <img with="12" height="12" [src]="category.image"> {{category.viewValue}}
              </mat-option>
            </mat-select>
          </mat-form-field>
          <mat-form-field class="text-overflow text-size-4
                  resizeMatSelect" *ngSwitchCase="'indicator_activity_daily'">
            <mat-select [(value)]="selectedActivity">
              <mat-select-trigger>
                <img with="12" height="12" [src]="selectedActivity"> {{selectedActivity}}
              </mat-select-trigger>
              <mat-option *ngFor="let activity of categories" [value]="activity.image">
                <img with="12" height="12" [src]="activity.image"> {{activity.viewValue}}
              </mat-option>
            </mat-select>
          </mat-form-field>
        </div>
      </td>
    </ng-container>
    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
  </table>
  <mat-paginator #paginator [length]="dataSource.filteredData.length" [pageIndex]="0" [pageSize]="5" [pageSizeOptions]="[5, 10, 20]">
  </mat-paginator>
</section>
</section>
</div>
efzxgjgh

efzxgjgh1#

您的示例中缺少很多内容,因此我将通过一个代码示例来端到端地解释这一点。您在组件中声明MatPaginator。由于您正在执行搜索,因此您需要绑定到长度、页面大小、页面索引,并处理(page)事件。您的API结果应该返回数据加上长度。如果您没有执行服务器端分页,您可以忽略它,只将其设置为返回结果的数组长度。“getPagedData”函数是设置API调用和处理结果的地方
从你的例子看,这两个东西似乎是缺失的部分,所以与下面的代码比较并调整,它将为你工作。
您的HTML模板:

<table mat-table [dataSource]="dataSource">
    <!-- columns here -->

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

<mat-paginator 
    #paginator
    (page)="pageChangeEvent($event)"
    [length]="totalRecords"
    [pageSize]="pageSize"
    [pageIndex]="pageIndex"
    [length]="totalRecords"
    [pageSizeOptions]="[5, 10, 20, 50, 100]"
    showFirstLastButtons>
</mat-paginator>

在组件TS中:

@ViewChild('paginator', { static: true }) paginator: MatPaginator;
dataSource = new MatTableDataSource<ApidatumDisplay>([]);
displayedColumns: string[] = //... set columns here
totalRecords = 0;
pageSize = 10;
pageIndex = 0;

getPagedData() {
    const search = {
      // ... set filters here
    };

    this.searching = true;
    this.service.search(search).subscribe({
      next: ((results) => {
        this.totalRecords = results?.length ? results[0].totalRecords : 0;
        this.dataSource.data = results || [];
      }),
      complete: () => this.searching = false,
      error: () => this.searching = false,
    });
  }
    
    
pageChangeEvent(event: PageEvent) {
    this.pageIndex = event.pageIndex;
    this.pageSize = event.pageSize;
    this.getPagedData();
}
1sbrub3j

1sbrub3j2#

要将分页添加到角形材料表(即mat-table),我们可以使用mat-paginator组件。
mat-paginator选择器是称为MatPaginator的Angular 材质模块的一部分。
参考:https://www.angularjswiki.com/material/mat-table-pagination/#pagination-in-mat-table

相关问题