angular - 角表排序,没有角材料
问题描述
我想在我的表格中搜索,但我希望表格中填充我的数据。目前,只有在我开始在搜索栏中输入时才会填写。
我认为问题出在初始化组件时 productsArray 为空
我的数据来自项目中的 JSON 文件。
下面你可以看到我目前拥有的
export class TableComponent implements OnInit {
searchText: any;
productsArray: Products[] = [];
filteredArray = [...this.productsArray];
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.getProducts().subscribe((res) => {
this.productsArray = res;
});
}
getProducts(): Observable < Products[] > {
return this.http
.get < any > ('assets/mock.data.json')
.pipe(map((results) => results.data));
}
filterArray(): any {
if (!this.productsArray.length) {
this.filteredArray = [];
return;
}
if (!this.searchText) {
this.filteredArray = [...this.productsArray];
return;
}
const products = [...this.productsArray];
const properties = Object.keys(products[0]);
this.filteredArray = products.filter((product) => {
return properties.find((property) => {
const valueString = product[property].toString().toLowerCase();
return valueString.includes(this.searchText.toLowerCase());
}) ?
product :
null;
});
}
}
代码名称类别
<tbody *ngFor="let product of filteredArray; let i = index">
<tr>
<td>{{ product.code }}</td>
<td>{{ product.name }}</td>
<td>{{ product.category }}</td>
</tr>
</tbody>
解决方案
初始化时filteredArray
,它是空的。只有在被调用filteredArray
时才会填充一些值。所以在 ngOnInit() 中filterArray()
提供值。filteredArray
尝试这个:
ngOnInit(): void {
this.getProducts().subscribe((res) => {
this.productsArray = res;
this.filteredArray = [...this.productsArray];
});
}
推荐阅读
- django-rest-framework - 如何通过客户端处理延迟加载数据表?
- python - 将零填充到 Python 列表
- r - 有没有办法使用 tm_layout 自定义图例直方图
- hibernate - Kotlin:即使我全部使用 kotlin-maven 插件,为什么休眠实体类是最终的?
- python - 如何使用 Selenium 在下拉列表中选择项目?
- php - 在第二页上将 php 返回到 html 的问题
- python - FindContours 仅支持 CV_8UC1 图像
- javascript - 关于javascript中while循环的问题
- c# - Google Cloud Vision API - client.DetectText 正在跳过 0
- processing - 处理中的 Draw() 不更新屏幕