I used angular material 2 to display a table of data as an order each row. I instantiated currentTradesData = new MatTableDataSource();
then initialize it in ngOnInit
. The next action is when I cancel an order, the api returned a successful result, but that order row still shows cancel button
in status
cell instead of showing closed
there, even thought I called method updateTableData
to reinitialize the data source.
Below is my code:
order-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;
}
}
view:
<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>