How to Group Data With an Angular Filter

Oluwafisayo Oluwatayo Feb 02, 2024
  1. Group Data in Angular With the filter Function
  2. Group Data in Angular With Pure HTML
  3. Group Data in Angular With ngFor
  4. Conclusion
How to Group Data With an Angular Filter

Web pages are used for multiple reasons. We have websites designed to solve problems; some are designed for education purposes.

In such instances, these websites might need to display items in classified presentations. Items present in classes are needed to show where each item belongs, like presenting data in the class of countries, states, districts, etc.

We will look at different ways to group items using the Angular framework.

Group Data in Angular With the filter Function

This first method will display the data into groups and feature a search engine with filter capability.

We start by creating a new project folder, and then we need to create two more files inside the src>>app folder of the project folder.

The first file will be named cars.ts; this will contain the data we want to group in the form of an array. The second file will be named filter.pipe.ts; this is where we create the pipe function for the search filter.

We will now navigate to the app.component.html file of the project folder and type in these codes.

Code Snippet- app.component.html:

<div class="container">
  <h2 class="py-4">Cars</h2>
  <div class="form-group mb-4">
    <input class="form-control" type="text" [(ngModel)]="searchText" placeholder="Search">
  </div>
  <table class="table" *ngIf="(cars | filter: searchText).length > 0; else noResults">
    <colgroup>
      <col width="5%">
      <col width="*">
      <col width="35%">
      <col width="15%">
    </colgroup>
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Brand</th>
        <th scope="col">Model</th>
        <th scope="col">Year</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let car of cars | filter: searchText; let i = index">
        <th scope="row">{{i + 1}}</th>
        <td>{{car.brand}}</td>
        <td>{{car.model}}</td>
        <td>{{car.year}}</td>
      </tr>
    </tbody>
  </table>
  <ng-template #noResults>
    <p>No results found for "{{searchText}}".</p>
  </ng-template>
</div>

Here, we have created the structure for the page and the grouping format for our data, and then we declared the *ngFor function to the headings to enable the search filter.

Next, we will move to the app.component.ts file to type in these few codes.

Code Snippet- app.component.ts:

import { Component } from '@angular/core';
import { CARS } from './cars';
interface Car {
  brand: string;
  model: string;
  year: number;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'filterone';
  cars: Car[] = CARS;
  searchText: string;
}

All we have done here is declare the data we want to group. For the brand, model, and the type of input inside the search field, we have declared them as string types while we have declared the type number for the year of the car model.

Now we need to move to the car.ts file we created earlier to insert the data we want to group. We will type in these codes.

Code Snippet- cars.ts:

export const CARS = [
    {
      brand: 'Audi',
      model: 'A4',
      year: 2018
    }, {
      brand: 'Audi',
      model: 'A5 Sportback',
      year: 2021
    }, {
      brand: 'BMW',
      model: '3 Series',
      year: 2015
    }, {
      brand: 'BMW',
      model: '4 Series',
      year: 2017
    }, {
      brand: 'Mercedes-Benz',
      model: 'C Klasse',
      year: 2016
    }
  ];

Here we have typed in the data that we want to group in the form of an array, and each is in the data type we declared in the app.component.ts file.

Next, we will navigate the filter.pipe.ts file and type these codes.

Code Snippet- filter.pipe.ts:

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

@Pipe({
  name: 'filter'
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {
    if (!items) return [];
    if (!searchText) return items;
    return items.filter(item => {
      return Object.keys(item).some(key => {
        return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
      });
    });
   }
}

What the pipe function does is that it detects the change in the grouped data and returns the new value after the change has occurred.

So we declare the items that could be changed inside the transform() function, and then we use the if statement to tell Angular that once a change occurs in the declared items, return the items that have been filtered. When we type in an element in the search bar, we see the page returning items related to the words we type.

Finally, we will do some work inside the app.module.ts file.

Code Snippet- app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FilterPipe } from './filter.pipe';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    FilterPipe
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This is where we import the modules that allow our application to function. Also, we declared the Filterpipe component from filter.pipe.ts.

Output:

Angular Group Data With the filter Function

Group Data in Angular With Pure HTML

When you look at the structure of grouped data, we can easily code it out using pure HTML, which is what we will do in this example.

Inside the app.component.html file is where we will do all the coding.

Code Snippet- app.component.html:

<ol class="list-group list-group-light list-group-numbered">
  <li class="list-group-item d-flex justify-content-between align-items-start">
    <div class="ms-2 me-auto">
      <div class="fw-bold"><h4>Fruits</h4></div>
      <ol>Pineapple</ol>
      <ol>apple</ol>
      <ol>Pine</ol>
    </div>
  </li>
  <li class="list-group-item d-flex justify-content-between align-items-start">
    <div class="ms-2 me-auto">
      <div class="fw-bold"><h4>Cars</h4></div>
      <ol>BMW</ol>
      <ol>Benz</ol>
      <ol>Audi</ol>
    </div>
  </li>
  <li class="list-group-item d-flex justify-content-between align-items-start">
    <div class="ms-2 me-auto">
      <div class="fw-bold"><h4>Countries</h4></div>
      <ol>US</ol>
      <ol>Italy</ol>
      <ol>France</ol>
    </div>
  </li>
</ol>

We declared the headers of each group inside an h4 tag to make them appear bigger than the items we are classifying. Then we declared each item inside an ordered list tag.

Output:

Angular Group Data With Pure HTML

Group Data in Angular With ngFor

The ngFor directive is Angular’s inbuilt function that lets us utilize local data that are presented in the form of an array. It organizes the data to be displayed in the form of grouped data.

We will create a new project folder, navigate to the app.component.ts file, and type in these codes.

Code Snippet- app.component.ts:

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'filterone';
  listofStatesCity : any[]=
  [
    {'State' : 'Karnataka', 'City':[{'Name': 'Bengaluru'}, {'Name': 'Mangaluru'}]},
    {'State' : 'Tamil Nadu', 'City':[{'Name': 'Chennai'}, {'Name': 'Vellore'}]},
    {'State' : 'Jharkhand', 'City':[{'Name': 'Ranchi'}, {'Name': 'Bokaro'}]}
  ]
}

We are grouping the data under two classes, State and City. We have declared the names of the states and cities under each group.

Then we will navigate to the app.component.html to create the structure for the array data.

Code Snippet- app.component.html:

<ul *ngFor = "let state of listofStatesCity">
  <li>{{state.State}}</li>
  <ul *ngFor = "let city of state.City">
      <li>
        {{city.Name}}
      </li>
  </ul>

We declared the ngFor directive for each group, so when the data is rendered on the web page, the data is classified under State and City.

Output:

angular group data with ngfor

Conclusion

We can group data using different methods inside the Angular framework. The reasons for grouping data could determine the approach we will adopt, especially with the pipe function that allows us to create search filter options.

Oluwafisayo Oluwatayo avatar Oluwafisayo Oluwatayo avatar

Fisayo is a tech expert and enthusiast who loves to solve problems, seek new challenges and aim to spread the knowledge of what she has learned across the globe.

LinkedIn

Related Article - Angular Filter