【发布时间】:2020-11-28 06:21:20
【问题描述】:
我正在尝试使此代码在 Angular 项目中工作,在 vanilla JS 中工作正常,但我在 Typescript 中的 for 循环遇到问题,现在在我的 Angular 视图中,我只打印带有 * 的产品列表ngFor 但我需要按类别分开。我希望用 map() 或 filter() 等数组方法替换 for 循环,但我不知道该怎么做。如何使用 Angular *ngFor 实现这一点?
var products = [
{id: 1, name: 'Apple', category: 'Fruit'},
{id: 2, name: 'Orange', category: 'Fruit'},
{id: 3, name: 'Blueberry', category: 'Jam'},
{id: 4, name: 'Sugar', category: 'Sweet'},
{id: 5, name: 'Candy', category: 'Sweet'},
{id: 6, name: 'Cheese', category: 'Cheese'}
];
//get categories
let categories = [];
for (let i = 0; i < products.length; i++) {
if(!categories.includes(products[i].category)){
categories.push(products[i].category);
}
}
console.log(categories);
//get products by category
for(item of categories){
console.log(item);
let filtered = products.filter(x => x.category == item);
console.log(filtered);
}
/*
Expected output
Fruit
{id: 1, name: 'Apple', category: 'Fruit'},
{id: 2, name: 'Orange', category: 'Fruit'},
Jam
{id: 3, name: 'Blueberry', category: 'Jam'},
Sweet
{id: 4, name: 'Sugar', category: 'Sweet'},
{id: 5, name: 'Candy', category: 'Sweet'},
Cheese
{id: 6, name: 'Cheese', category: 'Cheese'}
*/
角度视图:
<div>
<div *ngFor="let product of products">
<div class="card-body">
<p>{{product.name}}</p>
<p>{{product.category}}</p>
</div>
</div>
</div>
【问题讨论】:
-
不完全是胡安,谢谢
-
“已过滤”不包含您需要的内容?
-
在 vanilla JS 中工作正常,我在使用 typescript 时遇到了问题,我只是在寻找一种用数组方法而不是循环来组织它的方法。
标签: javascript angular typescript