0
votes

I want to make search box in angular 7 cli project. My project back-end was asp.net core web api. i will show array of data set, i want to make search box in angular front-end application. how to make that.

angular 7 cli

Below array of data come from asp.net web api

[
  {
    "productId": 1,
    "productName": "product 1",
    "productPrice": 500,
    "productDescription": "Des 1 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 1",
    "productAvailability": 0
  },
  {
   "productId": 2,
   "productName": "product 2",
   "productPrice": 1000,
   "productDescription": "Des 2 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
   "productCategory": "cat 2",
   "productAvailability": 0
   },
   {
    "productId": 3,
    "productName": "product 3",
    "productPrice": 2000,
    "productDescription": "Des 3 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 2",
    "productAvailability": 0
   },
   {
    "productId": 4,
    "productName": "PRODUCT 4",
    "productPrice": 3000,
    "productDescription": "Des 4 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 1",
    "productAvailability": 0
    } 
   ]

when i enter letter or number in search input box, only that input text related data will show in front end.

3

3 Answers

2
votes

BY USING Angular Pipe PROVIDED BY ANGULAR

Html Code

<input type="text" class="form-control" [(ngModel)]="searchText" placeholder="Search item" name="search"
    autocomplete="off">
    <div   *ngFor="let item of data| filterForUser : searchText; let i = index" >
<div> {{item.productId}}-{{item.productName}}</div>
</div>

Filter Component

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'filterForUser'
})
export class FilterPipeForUserSearch implements PipeTransform {
    transform(items: any[], searchText: string): any[] {
        if (!items || !searchText) return items;
        searchText = searchText.toLowerCase();
 return items.filter(it => {
            return it.productId==searchText;
        });      
    }

}

To Filter with the all the fields Use following filter Component

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
    name: 'filterForUser'
})
export class FilterPipeForUserSearch implements PipeTransform {
    transform(items: any[], searchText: string): any[] {
        if (!items || !searchText) return items;
        searchText = searchText.toLowerCase();
            return items.filter((data) => this.matchValue(data,searchText)); 
    }
    matchValue(data, value) {
        return Object.keys(data).map((key) => {
           return new RegExp(value, 'gi').test(data[key]);
        }).some(result => result);
      }
}

to show results, when user will type anything in search box only

    if (!items || !searchText) return [];

NOTE: Please declare FilterPipeForUserSearch in app / any other Module

0
votes

Oke lets try to explain. So what you have is your stored data that you show above.

You want to repeat filtering that data.

So first of all you make a copy of it when you collect your data.

Something like

this.historyData = data;

Then when you search you do:

this.data = this.historyData;

Now that part is done, now you want to filter so you do:

let searchedData = [];
for(let i = 0; i < this.data.length; i++) {
  let boolean = false;
  Object.getOwnPropertyNames(this.data[i]).map((key: string) = {
    if(this.data[i][key] === value) { boolean = true; }
  })
  if(boolean) { searchedData.push(this.data[i]); }
}
this.data = searchedData;

And when you value is empty you can do.

if(value === '') { this.data = this.historyData; }
else { //the above
0
votes

Hope I am not too late, but I have an alternative method apart from using Pipes. Basically, this approach requires you to get the keys/properties for the object, and then we iterate through the array to search for the term within each property.

const data = [{
    "productId": 1,
    "productName": "product 1",
    "productPrice": 500,
    "productDescription": "Des 1 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 1",
    "productAvailability": 0
  },
  {
    "productId": 2,
    "productName": "product 2",
    "productPrice": 1000,
    "productDescription": "Des 2 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 2",
    "productAvailability": 0
  },
  {
    "productId": 3,
    "productName": "product 3",
    "productPrice": 2000,
    "productDescription": "Des 3 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 2",
    "productAvailability": 0
  },
  {
    "productId": 4,
    "productName": "PRODUCT 4",
    "productPrice": 3000,
    "productDescription": "Des 4 enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni.",
    "productCategory": "cat 1",
    "productAvailability": 0
  }
];

function search(searchTerm) {
  const val = searchTerm.toLowerCase();
  const keys = Object.keys(data[0]);
  //console.log(keys)
  const searchResults = data.filter(item => {
    // iterate through each row's data by the properties
    for (let i = 0; i < keys.length; i++) {
      if (item[keys[i]].toString().toLowerCase().indexOf(val) !== -1 || !val) {
        return true;
      }
    }
  });
  console.log(searchResults);
  return searchResults;
}
search('Des 2 enim ipsam');