How To Apply Filters To *ngFor?


Basically, you need to write a pipe which you can use in the *ngfor directive.

In your component:

import { AfterViewChecked, Component, OnInit } from '@angular/core';

  selector: 'app-fillter',
  templateUrl: './fillter.component.html',
  styleUrls: ['./fillter.component.css']
export class FillterComponent implements OnInit, AfterViewChecked  {

  searchcountry:string = '';
  filterargs = {country: ''};
  items = [
    {country: 'india'},
    {country: 'japan'},
    {country: 'germany'},
    {country: 'united kingdom'},
    {country: 'france'},
    {country: 'italy'},
    {country: 'brazil'},
    {country: 'china'},
    {country: 'canada'},
    {country: 'united states'},
  constructor() { }

  ngOnInit(): void {

    this.filterargs = {country: this.searchcountry};
  ngAfterViewChecked() {;

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

<div class="header bg-gradient-danger pb-8 pt-5 pt-md-8">
  <div class="container-fluid">
    <div class="header-body">
      <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                class="form-control form-control-alternative"
        <div class="row mt-4 p-4">
        <div class="col-md-12">
            <ul class="p-4">
                <li *ngFor="let item of items | mycountryfilter:filterargs" class="list-text">
                    {{ }}

In your pipe: ( my-filter.pipe.ts)

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

    name: 'mycountryfilter',
    pure: false
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: any): any {
        if (!items || !filter) {
            return items;
        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  @compoent

import { MyFilterPipe } from './pipes/my-filter.pipe';

    imports: [
    declarations: [
    providers: [
    bootstrap: [AppComponent]
export class AppModule { }
NOTE: (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular. LINK


I hope you guys understand how I can do this.  Let me know if you face any difficulties.

You can watch my previous blog here.

Happy Coding {;} ????

Submit a Comment

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


Select Categories