[英]Angular Material Sort and paginator not displaying
我正在使用材料完成一個有角度的項目。 除了排序和分頁器功能外,一切正常。 我從文檔中添加了代碼,但是當我在瀏覽器中對其進行測試時,出現了小箭頭並且它們可以工作(我沒有收到任何錯誤消息)。 為什么它不起作用?
(我的數據存儲在數據庫中)
HTML
<table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">
<ng-container matColumnDef="name" >
<th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
<td mat-footer-cell *matFooterCellDef></td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Amount </th>
<td mat-cell *matCellDef="let element"> {{element.amount}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator color="accent" [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
打字稿
import { AfterViewInit, Component, ViewChild, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort, Sort } from '@angular/material/sort';
export class ExpenseComponent implements AfterViewInit, OnInit{
constructor() {}
displayedColumns: string[] = ['name', 'amount'];
dataSource = new MatTableDataSource(this.expense);
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
}
我想你有一個服務,不要導入服務的內容,只有一個函數可以返回一個帶有數據的 observable
getData()
{
return this.httpClient.get(....)
}
然后在你的組件中你有
displayedColumns: string[] = ['name', 'amount'];
dataSource:MatTableDataSource;
subscription:any;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor(dataService:DataService){}
ngOnInit()
{
this.subscription=this.dataService.getData().subscribe((res:any)=>{
//is in subscribe function where you create the dataSource
this.dataSource=new MatDataSource(res)
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.