Reputation: 165
I have a data provider in 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"
} ]
and here's my HTML file.
<div *ngFor="let location of locations">
<h1></h1>
<h2></h2>
</div>
In this scenario, how can I load a specific object (item) in data array with certain attributes?
For instance, If I want to load an object with "category" :"restaurant"
, what should I do on my HTML file? so the two others should not show up. I just want to load one out of three by using this specific attribute.
Thanks.
Upvotes: 2
Views: 1536
Reputation: 24324
You need to access the attribute. You can use the following example
<div *ngFor="let location of locations">
<h1>{{location.name}}</h1>
<h2>{{location.category}}</h2>
</div>
To filter depending on a category:
locationsFiltered = this.locations.filter(location =>location.category=="restaurant");
Now to make this example practical I will create a method to do it
filter(category : string) : any[] {
return this.locations.filter(location =>location.category==category);
}
then in html
<div *ngFor="let location of locationsFiltered">
<h1>{{location.name}}</h1>
<h2>{{location.category}}</h2>
</div>
Upvotes: 2