首页 > 解决方案 > 角度分页器未加载第一页

问题描述

首先,我知道有几个类似的问题,但我没有设法让它按照我想要的方式工作。这是任何人都可以向分页器询问的最简单的事情。立即加载第一页,无需按下一页和上一页按钮。

我的 HTML

<mat-paginator [length]="length"
               [pageSize]="pageSize"
               (page)="pageEvent = $event">

</mat-paginator>

<div  *ngIf="pageEvent">
    <mat-grid-list cols="2" rowHeight="7:1">
      <ng-container>
        <mat-grid-tile>
            pageIndex = {{ pageEvent.pageIndex }}
        </mat-grid-tile>
      </ng-container>
    </mat-grid-list>
</div>

和打字稿

import { Component, OnInit, ViewChild } from '@angular/core';
import { PageEvent } from '@angular/material/paginator';

@Component({
  selector: 'app-room',
  templateUrl: './room.component.html',
  styleUrls: ['./room.component.css']
})
export class RoomComponent implements OnInit {

  // MatPaginator inputs
  length = 6;
  pageSize = 1;

  // MatPaginator output
  pageEvent: PageEvent;

  constructor() { }

  ngOnInit(): void {}

}

像这样这样的帖子的答案不起作用。

任何帮助将不胜感激!

编辑:我发布了整个 ts 文件。

标签: angularpaginationangular-material

解决方案


您在事件上使用 *ngIf (在触发它之前它不会真正具有价值)

但是,您可以执行以下操作:

TS:

ngOnInit(): void {
    this.pageEvent = new PageEvent();
  }

  getPageIndex(){
      if (!this.pageEvent.pageIndex)
      {
        return 0;
      }
      else
      {
        return this.pageEvent.pageIndex;
      }
    }

然后是 HTML,只需调用函数:

<div  *ngIf="pageEvent">
    <mat-grid-list cols="2" rowHeight="7:1">
      <ng-container>
        <mat-grid-tile>
            pageIndex = {{getPageIndex()}}
        </mat-grid-tile>
      </ng-container>
    </mat-grid-list>
</div>

推荐阅读