Angular ngFor显示限制项目,然后单击以显示下一个

问题描述 投票:0回答:2

我正在使用ngFor但是我希望我的ngFor每页只显示3个项目,然后当我点击下一个时它会在另一个页面上显示下3个项目,这意味着第1页显示3个项目(1,2,3)第2页显示3个项目(4,5,6)等等,就像我们搜索Google并点击下一个或“第2页”以在第2页上显示更多结果一样。我正在使用切片,但这还不够。我坚持想法所以我真的需要你的帮助,如果你们知道这个问题的关键词,请告诉我。非常感谢。

这是我的* -component.html:

<section class="commentSection">
  <div class="comment" *ngFor="let item of reviewComments | slice:0:3">
      <div class="text">
        <div class="textContent" [innerHTML]="item.contentcomment"></div>
      </div>
      <div class="info">
        {{item.nameReviwer}} | {{item.date}}
      </div>
    </div>
  </div>
</section>

这是我的* -component.ts“:

getComments(bookId) { //get comment follow bookId
    this.bookService.getComment(bookId).subscribe(res => {
      console.log(res);
      this.reviewComments = res as ReviewComment[];
      console.log('List Comment: ', this.reviewComments);
    }, err => {
      console.log(err);
    });
}

这是我的* .service.ts

getComment(bookId: string): Observable<any> {
        const headers = new HttpHeaders({ 'Content-type': 'application/json' });
        return this.http.get(environment.apiBaseUrl + '/getcmtbook/' + bookId, { headers: headers }).catch(err => {
          return Observable.throw(err);
        });
}
angular ngfor
2个回答
0
投票

一个更简单有效的方法是使用Angular Material Paginator

文档中提到的示例是自解释的,易于遵循。

Ngx-Pagination也是快捷简便的方法。 https://www.npmjs.com/package/ngx-pagination


0
投票

您可以在for循环中使用Mat-Paginator组件:

HTML代码:

<div *ngFor="let obj of collection">
    <h3>{{obj}}</h3>
</div>
<mat-paginator [length]="100" [pageSize]="defaultRecords" [pageSizeOptions]="[5, 10, 25, 100]" (page)="pageEvent = $event; onPaginateChange($event)">
</mat-paginator>

TS代码:

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material';
/**
 * @title Paginator
 */
@Component({
  selector: 'paginator-overview-example',
  templateUrl: 'paginator-overview-example.html',
  styleUrls: ['paginator-overview-example.css'],
})
export class PaginatorOverviewExample implements OnInit {

  @ViewChild(MatPaginator) paginator: MatPaginator;

  temp: string[] = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];

  collection : any[] = []

  defaultRecords: any = 5;
  ngOnInit() {
    this.collection = this.temp.slice(0, this.defaultRecords);
  }
  onPaginateChange(data) {
    this.collection = this.temp.slice(0, data.pageSize);
  }
}

Updated_Stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.