我从Angular Material实现了Angular datatable。
我从我的API读取数据并使用以下代码填充我的表:
@ViewChild('filter') filter: ElementRef;
dataSource: MyDataSource | null;
dataSubject = new BehaviorSubject<any[]>([]);
displayedColumns = ['name'];
constructor(private appService: ApplicationsService) {
this.appService.getAllApps().subscribe({
next: value => this.dataSubject.next(value)
});
}
ngOnInit() {
this.dataSource = new MyDataSource(this.dataSubject);
}
export class MyDataSource extends DataSource<any[]> {
constructor(private subject: BehaviorSubject<any[]>) {
super ();
}
connect (): Observable<any[]> {
return this.subject.asObservable();
}
disconnect ( ): void {
}
}
我的模板:
<md-table #table [dataSource]="dataSource">
<!--- Note that these columns can be defined in any order.
The actual rendered columns are set as a property on the row definition" -->
<!-- name Column -->
<ng-container mdColumnDef="name">
<md-header-cell *mdHeaderCellDef> Name </md-header-cell>
<md-cell *mdCellDef="let row" (click)="viewApp(row)"> {{row.name}} </md-cell>
</ng-container>
<md-header-row *mdHeaderRowDef="displayedColumns"></md-header-row>
<md-row *mdRowDef="let row; columns: displayedColumns;"></md-row>
</md-table>
我试图在用户点击按钮时更新表格:
buttonClick() {
this.appService.geAnotherApps()
.subscribe({
next: value => this.dataSubject.next(value)
});
}
但表格没有更新。
答案 0 :(得分:0)
一种解决方案是在HTML中定义一个“操作列”,如下所示:
<ng-container matColumnDef="actions">
<mat-cell *matCellDef="let model">
<button mat-icon-button matTooltip="Edit" (click)="edit(model)">
<mat-icon>edit</mat-icon>
</button>
</mat-cell>
</ng-container>
如果在应用版本后传递完整元素进行编辑,则可以看到自动刷新表格。
在.ts文件中,您将看到以下内容:
private edit(element?: Model) {
// In this case i use Mat-Dialog from edition
let dialogRef = this.dialog.open(EditDialogComponent,
{
panelClass: 'mat-dialog-lg',
data: { element: element }
});
dialogRef.afterClosed().subscribe(response => {
if (response) {
// For change the data in the table list you have to assign the response to your element
element = response;
}
});
}
请记住,元素和响应必须属于同一类型