这里是我的Angular模板网格列表代码
<mat-grid-list cols=3 gutterSize="5px" style="text-align: center;">
<mat-grid-tile *ngFor="let item of items" >
<mat-card-content>
<mat-list >
<mat-list-item >
<p matLine>
<img mat-card-image src="{{item.photo}}" alt="Shoping Item" style="height: 80px; width: 100px;">
</p>
<p matLine>
<mat-card-title class="item_title">{{item.title}}</mat-card-title>
</p>
<p matLine>
<span class="price">Rs. <span >{{item.price}}</span></span>
</p>
</mat-list-item>
</mat-list>
</mat-card-content>
</mat-grid-tile>
</mat-grid-list>
我通过以下TS代码发送数据
ngOnInit(): void {
var url ="http://54.25.52.315:3000/api/items";
this.http.get(url,{responseType: 'text'}).subscribe(
(data :any) =>{
var obj = JSON.parse(data);
for (let i=0; i<obj.length; i++){
var img="http://54.25.52.315:3000/"+obj[i].photo;
this.items.push({id: obj[i].id,
title: obj[i].title,
price : obj[i].price,
categoty:obj[i].category,
photo: img});
}
}
);
}
在这段代码中,我成功地将数据传递到了网格列表中。可以通过点击按钮将新的过滤数据集重置并加载到同一网格列表
例如:-
<button (click)="fashionCategoty()">
使用这个按钮如何过滤和只加载类别=";时尚;项目到同一网格列表
假设您的类别是"时尚",则使用filter方法过滤列表。要过滤列表中的数据,您可以使用以下代码
fashionCategoty(){
this.items = this.items.filter(item => item.category === 'fashion')
}
如果你想重置过滤器,你可以有另一个名为allItems的列表来保存所有初始项目
例如,您可以修改ngOnInit函数,如下所示
ngOnInit(): void {
var url ="http://54.25.52.315:3000/api/items";
this.http.get(url,{responseType: 'text'}).subscribe(
(data :any) =>{
var obj = JSON.parse(data);
for (let i=0; i<obj.length; i++){
var img="http://54.25.52.315:3000/"+obj[i].photo;
this.items.push({id: obj[i].id,
title: obj[i].title,
price : obj[i].price,
categoty:obj[i].category,
photo: img});
this.allItems.push({id: obj[i].id,
title: obj[i].title,
price : obj[i].price,
categoty:obj[i].category,
photo: img});
}
}
);
}
在这种情况下,您的过滤方法将是
fashionCategoty(){
this.items = this.allItems.filter(item => item.category === 'fashion')
}
这样,您就不会丢失最初加载的数据,还可以根据需要进行筛选和重置。
有多种方法可以应用过滤器。我会提供一种方法,让你不记得http.get
在TS文件中,创建一个新字段来存储应显示的项目。默认为所有项目:
this.http.get(url,{responseType: 'text'}).subscribe(
(data :any) => {
const obj = JSON.parse(data);
for (let i=0; i<obj.length; i++){
this.items.push({...obj[i], photo: `http://54.25.52.315:3000/${obj[i].photo}` });
}
this.itemsToShow = this.items;
}
);
在您的模板中,循环通过itemsToShow
而不是
<mat-grid-tile *ngFor="let item of itemsToShow" >
对于fashionCategoty()
功能,将itemsToShow
设置为items
的过滤版本
fashionCategoty() {
this.itemsToShow = this.items.filter(item => item.category === 'fashion');
}