DEV Community

Tizhad
Tizhad

Posted on

Filter in Angular with code example

Being honest, I'm not a senior developer, but I do want to share things that I'm learning. Hopefully, it can be helpful.

If you are looking for an answer for this question " How can I filter an array in Angular", this post can help you.
I'm going to answer with an example:

You have an array of cars:

cars: ICar[] = [
    {
      'carId': 1,
      'carName': 'Toyota',
      'carCode': 'CAR-0023',
      'releaseDate': 'March 18, 2019',
      'description': 'this is a description',
      'price': 35000,
      'starRating': 4.2,
      'imageUrl': 'https://images.unsplash.com/photo-1525609004556-c46c7d6cf023?ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Y2Fyc3xlbnwwfHwwfHw%3D&ixlib=rb-1.2.1&w=1000&q=80'
    },
    {
      'carId': 2,
      'carName': 'Bugatti test',
      'carCode': 'CAR-1123',
      'releaseDate': 'March 18, 2020',
      'description': 'this is a description 2',
      'price': 48000,
      'starRating': 3.2,
      'imageUrl': 'https://stat.overdrive.in/wp-content/odgallery/2020/06/57263_2020_Mercedes_Benz_GLS.jpg'
    },
    {
      'carId': 3,
      'carName': 'BMW test 2',
      'carCode': 'CAR-0030',
      'releaseDate': 'March 18, 2018',
      'description': 'this is a description 3',
      'price': 80000,
      'starRating': 5,
      'imageUrl': 'https://www.focus2move.com/wp-content/uploads/2021/02/Bugatti-Divo_Lady_Bug-2020-1024-0b.jpg'
    },
    {
      'carId': 4,
      'carName': 'Benz',
      'carCode': 'CAR-0190',
      'releaseDate': 'March 18, 2021',
      'description': 'A description',
      'price': 50000,
      'starRating': 4.5,
      'imageUrl': 'https://cdn.motor1.com/images/mgl/8e8Mo/s1/most-expensive-new-cars-ever.webp'
    }
  ]
Enter fullscreen mode Exit fullscreen mode

I know that the images are not fit with the car name. :)

This is in ts file. for example cars.component.ts

Now we can take a look at HTML file:

<div class="card">
  <div class="card-header">
    {{title }}
  </div>
  <div class="card-body">
    <div>
      <div class="col-md-2 align-items-baseline"> Filter By: </div>
      <div class="col-md-4">
        <input type="text"
               placeholder="Type to search"
               [(ngModel)]="filterTerm"
               (ngModelChange)="filter()"
        >
      </div>
      <div class="row">
        <div class="col-md-6">
          <h4> Filtered by</h4>
        </div>
        <div class="table-responsive">
          <table *ngIf="cars && cars.length" class="table">
            <thead>
            <tr>
              <th>
                <button class="btn btn-primary" (click)="toggleImage()"> {{isImageVisible? 'Hide Image' : 'Show Image'}}</button>
              </th>
              <th>Car Name</th>
              <th>Car Code</th>
              <th>Release Date</th>
              <th>Price</th>
              <th>5 Star Rating</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let car of filteredCars">
              <td>
                <img src="{{car.imageUrl}}" class="small-img" title="car.imageUrl" *ngIf="isImageVisible">
              </td>
              <td>{{car.carName}}</td>
              <td>{{car.carCode}}</td>
              <td>{{car.releaseDate}}</td>
              <td>{{car.price}}</td>
              <td>{{car.starRating}}</td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

Enter fullscreen mode Exit fullscreen mode

As you see we have an input, where a user can write the car's name that s/he want to filter.
So here we need a [(ngModel)]="filterTerm" for getting the word and passing it to the component and (ngModelChange)="filter()" for the input changes and calling a function that I've called it filter()

filter(){
    if(this.filterTerm){
      this.filteredCars = this.cars.filter(car => car.carName.toLowerCase().includes(this.filterTerm.toLowerCase()))
    } else {
      this.filteredCars = this.cars
    }
}
Enter fullscreen mode Exit fullscreen mode

These are to variables that we need to declare them in our ts file.
filterTerm is a string such as "Toyota"
filterTerm: string = '';

and filteredCars is an arrays with type of ICar.
filteredCars: ICar[] = []

** ICar is an interface that I created for cars:

export interface ICar {
  carId : number;
  carName : string;
  carCode : string;
  releaseDate : string;
  description : string;
  price : number;
  starRating : number;
  imageUrl : string;
}
Enter fullscreen mode Exit fullscreen mode

You can create this file in the folder that you created for car files. I have it in cars folder(My cars component)

Discussion (1)

Collapse
diosvo profile image
Dios Vo

You can make it declarative (use Reactive form and observable).
[(ngModel)] is deprecated from version 6+