簡體   English   中英

Angular組件中的排序表

[英]Sort table in Angular component

我有兩個 Angular 組件,一個是加載另一個組件的整個頁面,它只是一個表格。

vs 代碼截圖

該表通過<app-detections-table [dataSource]="dataSource"></app-detections-table> detections.component.html
detections-table.component.html我添加了

<table
mat-table
[dataSource]="dataSource"
#sort
matSort="sort"
>

<th mat-header-cell *matHeaderCellDef mat-sort-header>Name</th>到每個列標題。
detections-table.component.ts我添加了

  ngAfterViewInit() {
  this.dataSource.sort = this.sort;
  }

現在,我得到了表格上的排序箭頭,但是當我單擊它們時沒有任何反應。
如果我從detections.component.html中刪除將 dataSource 傳遞給表組件,並且只在表組件中使用 JSON 對象,那么它會按預期工作,所以我假設在detections-table.component.ts中排序“為時已晚” ",這就是為什么我嘗試在detections.component.ts中將this.dataSource.sort = this.sort添加到ngOnInit()的末尾,但這也沒有做任何事情。
有人有小費嗎? 謝謝!

我在 mat-table 上遇到過類似的問題,我通過在 @Input 上使用 setter 並將表屬性加載到單獨的 function 中來解決它。

tableData = new MatTableDataSource([]);

@Input() set dataSource(value: any[]) {
    if(value) {
    this.loadTable(value);
    }
}

對於 loadTable,您可以執行以下操作:

loadTable(data: any[]) {
    this.tableData = new MatTableDataSource(data);
    this.tableData.sort = this.sort;
}

在此示例中,“tableData”變量成為您用於表的數據源,因此:

<table
mat-table
[dataSource]="dataSource"
#sort
matSort="sort"
>

會變成這樣:

<table
mat-table
[dataSource]="tableData"
#sort
matSort="sort"
>

希望這可以解決您的問題!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM