【问题标题】:Pagination in angular material from data fetched from an api从 api 获取的数据中的角度材料中的分页
【发布时间】:2018-12-08 11:43:25
【问题描述】:

我从 api 中获取了 100 多个用户的列表。现在我想在角度材料表中实现该数据。

是否有可能在前端我在 pageSize 中只显示 10 个用户并且有分页。我试过了,但它显示了所有可用的用户,尽管我已经实现了分页模块。

<mat-paginator [pageSize]="10" showFirstLastButtons></mat-paginator>

在打字稿代码中,我从父组件中获取列表。

import {Component, OnInit, ViewChild, Input, OnChanges} from '@angular/core';
import {MatPaginator, MatTableDataSource} from '@angular/material';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.scss']
})
export class UsersComponent implements OnInit, OnChanges {
  @Input() users;

  displayedColumns = ['name', 'id'];
  dataSource;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  constructor() { }

  ngOnChanges() {
    this.dataSource = new MatTableDataSource<any>(this.users);
  }

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
  }
}

【问题讨论】:

  • 你能出示你的.ts文件吗?
  • @mintquan 我已经更新了代码。我从父组件中获取了列表。所以我在ngOnChanges 上使用它来获取数据列表。
  • 在查看后尝试 Init hook ngAfterViewInit() { this.dataSource.paginator = this.paginator; }
  • @Vikas 它也不起作用

标签: angular pagination angular-material2


【解决方案1】:

真的不需要使用ngOnChanges,但是如果使用,则需要在ngOnChanges中指定datasource.paginator

另外,在分配给数据源时,请考虑分页器是否可见。

如果你在 ngOnInit 中使用你需要使用 static:true

@ViewChild(MatPaginator,{static:true}) paginator: MatPaginator;

但请记住,在这种情况下,分页器不能在 *ngIf 下,否则使用 ngAfterViewInit

顺便说一句,如果您可以访问 API 或分页器在服务器上 - 而不是在前端,您可以查看 this SO

【讨论】:

    【解决方案2】:

    不管怎样,我做到了。 将分页器放入ngOnChanges

    ngOnChanges() {
        this.dataSource = new MatTableDataSource<any>(this.users);
        this.dataSource.paginator = this.paginator;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2021-02-08
      相关资源
      最近更新 更多