我使用角度材质2来显示每行的数据表。我实例化了currentTradesData = new MatTableDataSource();
,然后在ngOnInit
中初始化它。下一个操作是当我取消订单时,api返回了一个成功的结果,但该订单行仍然在cancel button
单元格中显示status
而不是在那里显示closed
,甚至认为我调用了方法updateTableData
重新初始化数据源。
以下是我的代码:
阶history.component.ts:
export class OrderHistoryComponent implements OnInit {
openColumns = ['amount', 'status'];
resultsLength = 0;
pageSize = 5;
private paginator: MatPaginator;
private sort: MatSort;
@ViewChild(MatSort) set matSort(ms: MatSort) {
this.sort = ms;
this.setDataSourceAttributes();
}
@ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
this.paginator = mp;
this.setDataSourceAttributes();
}
currentTradesData = new MatTableDataSource();
currentTrades: Trades[] = [];
constructor(private apiService: ApiService,
private userService: UserService) { }
ngOnInit() {
this.getTrades();
}
getTrades() {
this.apiService.getTrades().subscribe((data: any) => {
this.currentTrades = data;
this.currentTradesData.data = this.currentTrades;
this.resultsLength = this.currentTradesData.data.length;
}, error => {console.log(error); });
}
cancelTrade(id) {
this.apiService.cancelTrade(id).subscribe((data) => {
this.updateTableData(data, id);
this.setDataSourceAttributes();
}, error => {console.log(error); });
}
private updateTableData(data: any[], id) {
const index = this.currentTrades.findIndex(x => x.id = id);
this.currentTrades[index].isClosed = true;
this.currentTradesData = data && data.length ? new MatTableDataSource(data)
: new MatTableDataSource(this.currentTrades);
this.resultsLength = this.currentTradesData.data.length;
this.setDataSourceAttributes();
}
setDataSourceAttributes() {
this.currentTradesData.paginator = this.paginator;
this.currentTradesData.sort = this.sort;
}
}
视图:
<mat-table [dataSource]="currentTradesData" matSort>
<mat-header-row *matHeaderRowDef="openColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: openColumns;"></mat-row>
<ng-container matColumnDef="amount">
<mat-header-cell *matHeaderCellDef mat-sort-header> Amount </mat-header-cell>
<mat-cell *matCellDef="let row">{{row.amount}}</mat-cell>
</ng-container>
<ng-container matColumnDef="status">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let row" class="text-center">
<button mat-raised-button class="cancel-btn" *ngIf="!row.isClosed" (click)="cancelTrade(row.id)" color="warn">
Cancel
</button>
<span *ngIf="row.isClosed == true">
<mat-chip color="primary" selected="true">Closed</mat-chip>
</span>
</mat-cell>
</ng-container>
</mat-table>
<mat-paginator [pageSize]="pageSize" [length]="resultsLength"></mat-paginator>
答案 0 :(得分:2)
您的问题是您无法更新网格的数据源可能此链接将帮助您完成它并让我知道是否有任何问题
Angular + Material - How To Refresh A Data Source (mat-table)