4

I have this data in in-memory-data.service.ts:

import {InMemoryDbService} from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const values = [
  {
    id: 0,
    title: 'Calculus',
    author: 'John Doe',
    date: '2018-05-15',
    content: 'Random text',
    category: 'Science'
  },
  {
    id: 1,
    title: 'Bulbasaur',
    author: 'John Doe',
    date: '2000-09-14',
    content: 'Random text',
    category: 'TV shows'
  },
  {
    id: 2,
    title: 'Fourier Analysis',
    author: 'John Doe',
    date: '2014-01-01',
    content: 'Random text',
    category: 'Science'
  }
];

return {values};
  }
}

Currently I am displaying the data in one of my components:

<ol class="list-unstyled mb-0">
  <li *ngFor="let value of values">{{value.title}}</li>
</ol>

How can I display only category "Science" values?

Ventura8
  • 81
  • 1
  • 1
  • 9

3 Answers3

9

You can filter it out using filter of java script which return new array containing your required data , like this :

this.filteredvalues = values.filter(t=>t.category ==='Science');

and then you can iterate over this filtered array

<li *ngFor="let value of filteredvalues ">{{value.title}}</li>
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
3

You can use array.filter to filter the matching values

const values = [
  {
    id: 0,
    title: 'Calculus',
    author: 'John Doe',
    date: '2018-05-15',
    content: 'Random text',
    category: 'Science'
  },
  {
    id: 1,
    title: 'Bulbasaur',
    author: 'John Doe',
    date: '2000-09-14',
    content: 'Random text',
    category: 'TV shows'
  },
  {
    id: 2,
    title: 'Fourier Analysis',
    author: 'John Doe',
    date: '2014-01-01',
    content: 'Random text',
    category: 'Science'
  }
];

let filteredvalues = values.filter(t=>t.category ==='Science');
console.log(filteredvalues);

So the matching HTML would be,

<ol class="list-unstyled mb-0">
  <li *ngFor="let value of filteredvalues ">{{value.title}}</li>
</ol>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
2

You can also have the filter logic isolated if you want it to be reusable. You can create a custom pipe using the filter condition you want. and then use the pipe in template as

<li *ngFor="let value of values | customFilter:filtercond">

and you can define the filtercond in your component as per your requirement

filtercond = {category: 'Science'};

similar issue is addressed here: apply filters to *ngFor

Avinash
  • 1,245
  • 11
  • 19