Filtering a List

The Angular team and other experienced Angular developers strongly recommend moving filtering and sorting logic into the component itself. We'll add them in our application.

First of all add this code inside 'product-list.component.ts'

filteredProducts: IProduct[];

Here, we have added new property for all products. Then, we'll remove static listfilter with cart text. ie 'listFilter: string = 'cart'' and instead add getter and setter method. It looks like this:

_listFilter: string;
get listFilter(): string {
  return this._listFilter;
}
set listFilter(value:string) {
  this._listFilter = value;
  this.filteredProducts = this.listFilter ? this.performFilter(this.listFilter) : this.products;
}

Here,
when the data needs the value, it will call 'get' method
when user modifies the value, it will call 'set' method.
'this.filteredProducts = ...' means we want to set our filter product array to the filter list of product. We used javascript conditional operator

We also have to add this method:
performFilter(filterBy: string): IProduct[] {
  filterBy = filterBy.toLocaleLowerCase();
  return this.products.filter((product: IProduct) => product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}

Here, we have used array prototype filter method. You can get more info here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

At last, we will use this code:
constructor() {
  this.filteredProducts = this.products;
  this.listFilter = 'cart';
}
this is used to set default value for more complex property.
'this.filteredProducts' means to show all product list
'this.listFilter' means default filter text being used in input

Final Code



Now in 'product-list.component.html', change the text from 'products' to 'filteredProducts'

Share this

Related Posts