2

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.

1 Answer 1

2

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>

EDIT

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>
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your response. Yes, I know how to do that. But my question is, If I want to load an object with "category":"restaurant" only, what should I do? the two others should not show up.
I want to be able to load one out of three.. by calling up a specific attributes for that object. How can I do that? Thanks I will wait for your edit.
Thanks for your edit! I really appreciate your help. I will try this now.
I just gave you the tools. I'll let use them. I advise to use a select list w3schools.com/bootstrap/…
For the final html, don't you need {{location.name}} and {{location.category}} between the header tags (as in your first html snippet)? (If so just edit and I'll delete my comment.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.