我在 Angular 5 中有一个数据提供程序。
export class DataProvider {
location: any;
private locations: any[] = [
{
"name": "restaurant",
"location": "downtown",
"category": "restaurant",
"id": "1"
},
{
"name": "law firm",
"location": "center city",
"category": "office",
"id": "2"
},
{
"name": "public library",
"location": "suburb",
"category": "library",
"id": "3"
} ]
这是我的 HTML 文件。
<div *ngFor="let location of locations">
<h1></h1>
<h2></h2>
</div>
在这种情况下,如何加载具有某些属性的数据数组中的特定对象(项目)?
例如,如果我想加载带有 "category":"restaurant"
的对象,我应该对 HTML 文件做什么?所以另外两个人不应该出现。我只想使用此特定属性加载三分之一。
谢谢。
最佳答案
您需要访问该属性。您可以使用以下示例
<div *ngFor="let location of locations">
<h1>{{location.name}}</h1>
<h2>{{location.category}}</h2>
</div>
编辑
根据类别进行过滤:
locationsFiltered = this.locations.filter(location =>location.category=="restaurant");
现在为了使这个示例更加实用,我将创建一个方法来实现它
filter(category : string) : any[] {
return this.locations.filter(location =>location.category==category);
}
然后在html中
<div *ngFor="let location of locationsFiltered">
<h1>{{location.name}}</h1>
<h2>{{location.category}}</h2>
</div>
关于javascript - 如何显示对象数组中的特定对象(Angular 5、TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49823736/