Angular材质分页器不能正常工作


新年快乐

我正在学习角,我在我的表上使用角材质分页器,它从API获取数据。它在底部正确显示行数和条目数,但所有数据仍然显示在单个页面中。我在网上搜索并尝试了很多解决方案,但都是徒劳的。

我正在使用一个显示在router-outlet中的视图密码组件。

组件HTML

<div class="mat-elevation-z8">
<table mat-table [dataSource]="passwords">
<!-- Position Column -->
<ng-container matColumnDef="S.No">
<th mat-header-cell *matHeaderCellDef> S.No. </th>
<td mat-cell *matCellDef="let password"> {{password.website}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="Website">
<th mat-header-cell *matHeaderCellDef> Website </th>
<td mat-cell *matCellDef="let password"> {{password.website}} </td>
</ng-container>
<!-- Weight Column -->
<ng-container matColumnDef="URL">
<th mat-header-cell *matHeaderCellDef> URL </th>
<td mat-cell *matCellDef="let password"> {{password.url}} </td>
</ng-container>
<!-- Symbol Column -->
<ng-container matColumnDef="Password">
<th mat-header-cell *matHeaderCellDef> Password </th>
<td mat-cell *matCellDef="let password"> {{password.password}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator showFirstLastButtons [pageSize]="5" [pageSizeOptions]="[5, 10, 25, 50]">
</mat-paginator>
</div>

组件ts

import { HttpClient } from '@angular/common/http';
import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { MatTableDataSource, MatTableDataSourcePaginator } from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
@Component({
selector: 'view-passwords',
templateUrl: './view-passwords.component.html',
styleUrls: ['./view-passwords.component.css']
})
export class ViewPasswordsComponent{
url:any= 'http://localhost:8080/showPass';
passwords:any;
displayedColumns: string[] = ['S.No', 'Website', 'URL', 'Password'];
dataSource: any;
@ViewChild(MatPaginator, {static:false}) paginator !: MatPaginator;
constructor(private http: HttpClient, private cdr:ChangeDetectorRef){
this.http.get(this.url)
.subscribe(Response=>{
(this.passwords=Response);
this.cdr.detectChanges();
this.dataSource= new MatTableDataSource(this.passwords);
this.dataSource.paginator = this.paginator;
//console.log(this.dataSource.paginator)
})
}

我localhost我的网页

底部分页器工作正常,我可以看到,但表显示所有的数据在一个页面,尽管分页器显示1-5。我做错什么了吗?

Angular材质分页器在多个页面中显示数据,但它在单个页面中显示所有数据

我重构并简化了你的typescript代码。我认为一个主要的问题是你传递passwords而不是dataSource到HTML。您能试试下面的代码是否有效吗?

组件TS:

@ViewChild(MatPaginator)
paginator!: MatPaginator;
url = 'http://localhost:8080/showPass';
displayedColumns: string[] = ['S.No', 'Website', 'URL', 'Password'];
dataSource!: MatTableDataSource<User>;
constructor(private http: HttpClient){
this.http.get(this.url).subscribe(res=>{
this.dataSource = new MatTableDataSource(res);
this.dataSource.paginator = this.paginator;
})
}

组件HTML:

<table mat-table [dataSource]="dataSource">

最新更新