-1

I need to filter only those objects whose categoria is a. Is there any way to achieve this using ngFor?

service.ts :

productos: Producto[] = [
  {id:'01', categoria:'a', titulo:'title1'},
  {id:'02', categoria:'b', titulo:'title2'},
  {id:'03', categoria:'a', titulo:'title3'},
  {id:'04', categoria:'c', titulo:'title4'},
  {id:'05', categoria:'c', titulo:'title5'}
]

getProductos() {
   return of(this.productos);
}

component.ts :

ngOnInit() {
  this.productos$ = this.ps.getProductos();
}

component.html :

<div *ngFor="let producto of productos$ | async">
  {{ producto.titulo}}
</div>
Paco Zevallos
  • 2,165
  • 7
  • 30
  • 68

2 Answers2

1

You can use a pipe ( refer to Vinit link ) or you can use a filter

getProductos() {
   return of(this.productos.filter( el => el.categoria == 'a'); 
}
wFitz
  • 1,266
  • 8
  • 13
  • This is a very good alternative, it worked for me. Thank you. I think there is a typo, it ended up like this: `getProductos() { return of (this.productos.filter ( el => el.categoria === 'a'));}` – Paco Zevallos Jul 24 '18 at 12:50
0

You can use filter operator to do it.

ngOnInit() {
     this.productos$ = this.ps.getProductos().pipe(filter(el => el.categoria == 'a'));
}
Ashish Gurjar
  • 291
  • 1
  • 3
  • 5