1

in my foods.service.ts, I have an array

[{
  "category": "dogfood", "flavor": "chicken",
  "category": "catfood", "flavor": "beef",
  "category": "birdfood", "flavor": "sunflower",
  "category": "dogfood", "flavor": "beef",
  "category": "dogfood", "flavor": "chicken"

}]

then in my food.component.html I have my loop:

 <ul>
  <li *ngFor = "let food of foods">
    <span>{{food.category}}</span>
  </li>
 </ul>

if I run it as such I get duplicate values of dogfood. what I ideally want is to only return a list with unique value. for instance, it should return:

  • dogfood
  • catfood
  • birdfood

as dogfood has already been displayed. I know I need to add a *ngIf to the span tag but not sure what to put there or even if this is the correct place to do so.

Gavin Wood
  • 955
  • 3
  • 14
  • 28
  • 1
    see https://stackoverflow.com/questions/57097662/how-to-get-unique-an-array-of-objects-back-from-a-complex-an-array-of-objects just filter the array before `*ngFor` – dota2pro Jul 23 '19 at 20:40
  • 1
    Possible duplicate of [How to apply filters to \*ngFor?](https://stackoverflow.com/questions/34164413/how-to-apply-filters-to-ngfor) – Dino Jul 23 '19 at 20:45
  • filter in your component and `*ngFor` over the updated array! – nircraft Jul 23 '19 at 20:45
  • You can either create a pipe that you will use in *ngFor or filter the array in your component – Dino Jul 23 '19 at 20:46
  • @Dino I would recommend avoiding a filter pipe for these reasons: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe – Andrew Hill Jul 23 '19 at 21:41

0 Answers0