Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

May 27, 2016

Angular 2: Filtering a List Using a Computed Property and Events

Filed under: Angular @ 1:10 pm
Tags: , , ,

In my Pluralsight course: “Angular 2: Getting Started”, I demonstrate how to filter a list of products for display using a custom pipe. However, using a custom pipe does not provide easy access to the filtered result. For example, say you also want the count of the filtered list so you can display “5 of 125” or access other information about the list. In these cases, it is best to filter without using a custom pipe. This post shows you one technique: using a computed property and the input event.

Additional techniques for solving this problem are:

This post updates the code available from my github repo. So starting with that code:

1. Change the declarations adding a productsFiltered computed property. The productsFiltered property will contain the filtered list of products.

pageTitle: string = ‘Product List’;
imageWidth: number = 50;
imageMargin: number = 2;
showImage: boolean = false;
listFilter: string;
errorMessage: string;
products: IProduct[];
productsFiltered: IProduct[];

2. Add an onFilterChanged event handler that executes each time the filter input box is changed:

onFilterChanged(event: any) {
    let filter = event.target.value;
    filter = filter ? filter.toLocaleLowerCase() : null;
    this.productsFiltered = filter ? this.products.filter((product: IProduct) =>
        product.productName.toLocaleLowerCase().indexOf(filter) !== -1) : this.products;
}

This code re-filters the list every time the listFilter input box changes.

This is not enough, however. When the page is first displayed the product array is empty so nothing appears on the page. We need to initialize the computed property when the product data is retrieved.

3. One way to set the computed property when the data is retrieved is to modify the ngOnInit() method as follows:

ngOnInit(): void {
       this._productService.getProducts()
                 .subscribe(
                   products => this.onProductsRetrieved(products),
                   error =>  this.errorMessage = <any>error);
}

When the products are retrieved, this code calls the onProductsRetrieved method.

4. Create the new onProductsRetrieved method as follows:

onProductsRetrieved(products: IProduct[]) {
     this.products = products;
    this.productsFiltered = products;

}

This code sets the retrieved products to our product property and initializes our computed property.

5. The only other changes are to the template:

<input type=’text’ (input)=’onFilterChanged($event)’ [(ngModel)]=’listFilter’ />

This binds the input event to the onFilterChanged event handler, passing in the event information.

NOTE: The input event is not supported in all browsers.

6. And change the template binding:

<tr *ngFor=’let product of productsFiltered‘>

This now binds to the productsFiltered property and no longer needs the pipe. We can then also bind other elements to this property or this property’s count method as needed.

Enjoy!

2 Comments

  1.   sam — April 8, 2017 @ 3:16 pm    Reply

    I can get data from a webApi through http.get from angular 2 but http.post does not work with both observables & promises.
    however it does work with in-memory-web-api but not .net webapi.
    you have not covered http.post.

    Many thanks

Trackbacks/Pingbacks

  1. Angular 2: Filtering a List Using a Computed Property and Setter -Deborah's Developer MindScape

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs