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

时间:2019-04-13 04:26:57

标签: angular ngfor

我正在使用ngFor,但我希望ngFor每页仅显示3个项目,然后单击“下一步”时,它将在另一页上显示接下来的3个项目,这意味着第1页显示3个项目(1,2 ,3)第2页显示3个项目(4,5,6),依此类推,就像我们搜索Google并单击next或“第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);
        });
}

2 个答案:

答案 0 :(得分:0)

您可以在forloop中使用 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

答案 1 :(得分:0)

一种更简单有效的解决方法是使用Angular Material Paginator

文档中提到的示例很容易解释,并且易于理解。

Ngx分页也是一种快速简便的方法。 https://www.npmjs.com/package/ngx-pagination