Categories
Angular Answers

How to apply filters to Angular *ngFor?

Spread the love

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 |.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *