Pesquisa de site

javascript - Como mostrar um objeto específico em um array de objetos (Angular 5, TypeScript)


Eu tenho um provedor de dados no 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"
    } ]

e aqui está meu arquivo HTML.

<div *ngFor="let location of locations">
   <h1></h1>
    <h2></h2>
</div>

Nesse cenário, como posso carregar um objeto específico (item) em um array de dados com certos atributos? Por exemplo, se eu quiser carregar um objeto com "category" :"restaurant", o que devo fazer no meu arquivo HTML? Assim, os outros dois não devem aparecer. Eu só quero carregar um de três usando esse atributo específico.

Obrigado.

Resposta #1

Você precisa acessar o atributo. Você pode usar o seguinte exemplo

<div *ngFor="let location of locations">
   <h1>{{location.name}}</h1>
    <h2>{{location.category}}</h2>
</div>

EDITAR

Para filtrar dependendo de uma categoria:

locationsFiltered = this.locations.filter(location =>location.category=="restaurant");

Agora, para tornar este exemplo prático, eu vou criar um método para fazê-lo

filter(category : string) : any[] {
   return this.locations.filter(location =>location.category==category);
}

então em html

<div *ngFor="let location of locationsFiltered">
   <h1>{{location.name}}</h1>
    <h2>{{location.category}}</h2>
</div>