How to apply filters to Angular *ngFor?

Sometimes, we want to apply filters to Angular *ngFor.

In this article, we’ll look at how to apply filters to Angular *ngFor.

How to apply filters to Angular *ngFor?

To apply filters to Angular *ngFor, we can apply a filter with the |.

For instance, we write

this.filterArgs = { title: "bar" };
this.items = [{ title: "foo" }, { title: "bar" }, { title: "baz" }];

in our component code.

Then in the template, we write

<li *ngFor="let item of items | myFilter: filterArgs ">
  ...
</li>

to apply the myFilter filter.

Then we create the myFilter filter by writing

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({
  name: "myFilter",
  pure: false,
})
export class MyFilterPipe implements PipeTransform {
  transform(items: any[], filter: Object): any {
    if (!items || !filter) {
      return items;
    }
    return items.filter((item) => item.title.includes(filter.title) );
  }
}

to create the MyFilterPipe class that we name as myFilter.

Then we add the transform method in the class.

We return the filtered results that we get after calling filter.

Now the myFilter filter will render the filtered results in the template.

Conclusion

To apply filters to Angular *ngFor, we can apply a filter with the |.