将材料表绑定到api节点表



我想将rest api数据源连接到材料表。这适用于简单的表格,但材料表格不显示任何数据。

这是工作正常的简单表的标记:

<!-- simple table -->
<table border="1">
<thead>
<tr>
<th>id</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let x of list_product">
<td>{{x.id}}</td>
<td>{{x.description}}</td>
</tr>
</tbody>
</table>
<!-- end of simple table -->

但这种材料表的标记并没有显示数据:

<!-- material table -->
<table mat-table>
<!-- Position Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let x of list_product"> {{x.id}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let x of list_product"> {{x.description}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<!-- end of material table -->

这是我从节点调用表的Typescript代码:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { analyzeAndValidateNgModules } from '@angular/compiler';
@Component({
selector: 'app-basic',
templateUrl: './basic.component.html',
styleUrls: ['./basic.component.scss']
})
export class BasicComponent implements OnInit {
public list_product:any=[];
displayedColumns: string[] = ['id', 'description'];
constructor(private http:HttpClient) { }
ngOnInit(): void {
this.get_data();
}
get_data()
{
this.http.get("http://localhost:3000/listp").subscribe(
(res)=>{ 
for(var i=0;i<res['length'];i++){
this.list_product.push(res[i]);
}
}//end res
)
}
}

您的简单表格和材料表格的工作方式不同。因此-

  1. 在模板中,需要将list_product绑定到mat-tabledataSource属性
  2. 在组件代码中,每次收到新的响应时都需要替换list_product——用项目逐个填充list_product不会更新表的dataSource

将您的表修改为-

<table mat-table [dataSource]="list_product">
<!-- Position Column -->
<ng-container matColumnDef="id">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let product"> {{product.id}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="description">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let product"> {{product.description}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

并将get_data()方法更改为-

get_data(){
this.http.get<any>("http://localhost:3000/listp").subscribe(
res => this.list_product = res
);
}

有关更多详细信息,请查看文档

我想要另一个帮助,这是我的表的分页,因为我的项目与web中的其他示例不同,我无法解决

最新更新