DEV Community

Atit Patel
Atit Patel

Posted on • Originally published at Medium

How to apply filters to *ngFor?

Angular Basics


As a developer, there is no limit to learning. We always need to be up to date with technologies as well as the upcoming or current features which are trending in the market.

Recently, I was looking for the best way to optimize my angular code. I have gone through a lot of articles and as we know it is limitless. Then I thought of consolidating the checklist for writing cleaner code for Angular which helped me and might help others too.

These small articles not only help you to write a better TypeScript or JavaScript Code but also clear the concepts of front-end technologies. This will help you to build your strong base and can help you in the upcoming frontend interviews.

One of the most basic topics in any programming is displaying data from services to the HTML. We do use various techniques to support this. One of the widely used directives for this *ngFor which works like for loop and iterate and display content as needed. What if we want to apply some filter while iterating the data. Let’s see one of the ways to achieve this.

When we have much bigger data and want to filter multiple items in the HTML , It will be like lot of conditions in HTML so it is better to create a pipe which can do a filtering and give us the data.

Let’s check the steps to create the filter pipe.

1. Component

filterargs = {title: 'hello'};
data= [{title: 'test abc'}, {title: 'test cde'}, {title: 'foo bar'}];

2. Template

In your template, you can pass string, number, or object to your pipe to use to filter on:

<li *ngFor="let data of data| filter:filterargs">

3. Pipe

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myfilter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: any[], filter: Object): any {
if (!items || !filter) {
return items;
}
// filter items array, items which match and return true will be
// kept, false will be filtered out
return items.filter(item => item.title.indexOf(filter.title) !== -1);
}
}

Remember to register your pipe in app.module.ts; you no longer need to register the pipes in your @Component

import { FilterPipe } from './shared/pipes/my-filter.pipe';
@NgModule({
imports: [
..
],
declarations: [
FilterPipe,
],
providers: [
..
],
bootstrap: [AppComponent]
})
export class AppModule { }

References:

How to apply filters to *ngFor?
Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results…stackoverflow.com

Top comments (0)