简体   繁体   English

角度垫分页器页面大小无法正常工作

[英]Angular mat-paginator page size not working correctly

I have created a mat-paginator element for a mat-table.我为 mat-table 创建了一个 mat-paginator 元素。 My issue is that the paginator is not correctly displaying the page size.我的问题是分页器没有正确显示页面大小。 It will display all the results on one page, despite the page size being 5.Here I am making a request to an API to get a list of transactions, then adding them to a list to be displayed in the table.尽管页面大小为 5,但它将在一页上显示所有结果。这里我向 API 发出请求以获取事务列表,然后将它们添加到列表中以显示在表中。 I have tried all the possible solutions I have found with no success.我已经尝试了我找到的所有可能的解决方案,但都没有成功。

export class txns implements OnInit {
      ELEMENT_DATA: ISalesOrders[] = []; 
      displayedColumns = ['type', 'source', 'amount']; 
      panelOpenState: boolean = false; 

      expandedElement: any;
      dataSource = new MatExpandTableDataSource(this.ELEMENT_DATA);
      config:any; //App Configuration
      errorLoading:boolean = false; 
      doneLoading:boolean = false; 




    @ViewChild('paginator') paginator: MatPaginator;//Creates horizontal link with paginator

    isExpansionDetailRow = (i: number, row: Object) => 
    row.hasOwnProperty('detailRow');//Determines whether the the row is expandable.

/**
 * Similar to constructor, NgINIT will wait until components dependencies are loaded.
 */
ngOnInit() {
    this.getMonthlySalesTransactions(3).subscribe(data => {
        console.log(data);
        data.forEach((data) => {
            if(data.result === 0) {
                let results = data.objs as ISalesOrders[];
                results.forEach(elem => {
                    this.ELEMENT_DATA.push(elem);
                });



            } else {
                this.errorLoading = false;
            }
            this.doneLoading = true;


        });
        this.dataSource = new MatExpandTableDataSource(this.ELEMENT_DATA);
        this.dataSource.paginator = this.paginator;

    });



}

And the html template:和 html 模板:

<div class="example-container mat-elevation-z8">
<p>{{ 'desc.recent-txns' | translate }}</p>
<mat-progress-bar mode="indeterminate" *ngIf="!doneLoading"></mat-progress-bar>
<h1 *ngIf="doneLoading && ELEMENT_DATA.length == 0">{{ 'no-transactions' }}</h1>
<mat-table #table [dataSource]="dataSource" *ngIf="ELEMENT_DATA.length != 0">

    <!-- Position Column -->
    <ng-container matColumnDef="type">
        <mat-header-cell *matHeaderCellDef> {{ 'transaction-type' | translate }} </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{ element.Brand_Group }} </mat-cell>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="source">
        <mat-header-cell *matHeaderCellDef> {{ 'source' | translate }} </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{ element.Source_Account_Name }} </mat-cell>
    </ng-container>

    <!-- Weight Column -->
    <ng-container matColumnDef="amount">
        <mat-header-cell *matHeaderCellDef> {{ 'amount' | translate }} </mat-header-cell>
        <mat-cell *matCellDef="let element"> {{ element.Original_Amount | currency:config.currencyCode}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="expandedDetail">
        <mat-cell *matCellDef="let detail">
            {{ 'transaction-id' | translate }}: {{ detail.element.Transaction_ID }} <br>
            {{ 'timestamp' | translate }}: {{ detail.element.Transaction_Time | date }} <br>
            {{ 'status' | translate }}: {{ detail.element.Status }} <br>
            {{ 'source-fees' | translate }}: {{ detail.element.Source_Fees_1 | currency:config.currencyCode }} <br>
        </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"
                     matRipple
                     class="element-row"
                     [class.expanded]="expandedElement == row"
                     (click)="expandedElement = row"></mat-row>
    <mat-row *matRowDef="let row; columns: ['expandedDetail']; when: isExpansionDetailRow"
                     [@detailExpand]="row.element == expandedElement ? 'expanded' : 'collapsed'"
                     style="overflow: hidden">
    </mat-row>



</mat-table>

<mat-paginator #paginator
                             [pageSize]="10"
                             [pageSizeOptions]="[5, 10, 20]"
                             [showFirstLastButtons]="true">
</mat-paginator>

Result:结果:

https://imgur.com/a/5WS0i4m https://imgur.com/a/5WS0i4m

but I only want 5 elements per page.但我只想要每页 5 个元素。 any help is appreciated任何帮助表示赞赏

i also want to have the ability to expand rows on click, so I created MatExpandTableDataSource class to let me do this.我还希望能够在单击时展开行,因此我创建了 MatExpandTableDataSource 类来让我这样做。 I believe this is were the problem is happening.我相信这是问题正在发生。 If I switch to use MatTableDataSource it works, but it does not work properly when using this class.如果我切换到使用 MatTableDataSource 它可以工作,但是在使用此类时它无法正常工作。

` `

export class MatExpandTableDataSource extends MatTableDataSource<any> {
/** Connect function called by the table to retrieve one stream containing 
the data to render. */
ELEMENT_DATA: ISalesOrders[];

/**
 * Constructor for ExpandableTableDataSource
 * @param ELEMENT_DATA
 */
constructor(ELEMENT_DATA: ISalesOrders[]) {
    super();
    this.ELEMENT_DATA = ELEMENT_DATA;
}

/**
 * Returns list of details listed inside expandable item
 * @returns {any} Observable<Element[]>
 */
connect(): any {
    const rows:any = [];
    this.ELEMENT_DATA.forEach(element => rows.push(element, { detailRow: true, element }));
    return of(rows);
}

disconnect() { }

} }

You have to make some kind of link between the table and mat-paginator component to communicate with each other which can be achieved via angular Page lifecycle hook AfterViewInit .您必须在tablemat-paginator组件之间建立某种链接才能相互通信,这可以通过 angular Page 生命周期钩子AfterViewInit 实现

    import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

     export class txns implements OnInit,AfterViewInit { 

      //MatPaginator is keyword here
      @ViewChild(MatPaginator) paginator: MatPaginator; 

     //declare your datasource like this 
      dataSource = new MatTableDataSource;

     //initialize your datasource like this 
      this.someservice.getData()
      .subscribe((data: any[]) => {
        this.dataSource .data = data as any;
      });

      //rest of your code..
      ngAfterViewInit(): void {   
            this.dataSource.paginator = this.paginator;
          }
        }

html #paginator must be there html #paginator 必须在那里

<mat-paginator #paginator
                             [pageSize]="10"
                             [pageSizeOptions]="[5, 10, 20]"
                             [showFirstLastButtons]="true">
</mat-paginator>

Using an *ngIf directive in mat-paginator will fix this.mat-paginator使用*ngIf指令可以解决这个问题。

<mat-paginator [length]="total"
               [pageIndex]="page_index"
               [pageSize]="per_page"
               [pageSizeOptions]="[10, 20, 50, 100]"
               showFirstLastButtons
               (page)="onChangedPageSize($event)"
               *ngIf="!doneLoading"> <!-- this line -->
</mat-paginator>

If you are trying to get data from an api, you can initialize the paginator after the result of the api call.如果您尝试从 api 获取数据,您可以在 api 调用的结果之后初始化分页器。

for example:例如:

this.myProvider.getData(...).subscribe(res=>{
    this.dataSource = new MatTableDataSource<...>(...);
    this.dataSource.paginator = this.paginator;
})

It works for me !这个对我有用 !

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM