usmanwalana usmanwalana - 1 month ago 31
TypeScript Question

Angular 2 - Case insenstive search using pipe

I have a working search pipe in my project. It is applied on a table. table has many columns such as product name, category, qty etc. The pipe searches through all the fields and filters the result. It is case sensitive and i want to make it case insensitive.
If i type

Mobile
it displays the results but if i type
mobile
it does not show results.

Search.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';
import {isObject} from "rxjs/util/isObject";
import {isEmpty} from "rxjs/operator/isEmpty";
import {empty} from "rxjs/Observer";
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform
{
transform(input, searchString)
{
if (input == null) return input;
return input.filter(this.compareWithAllFields, searchString);
}

compareWithAllFields(value, index)
{
var fields = Object.keys(value);
for (let i = 0; i < fields.length; i++)
{
if (value[fields[i]] != null)
{
if (isObject(value[fields[i]]))
{
var childFields = Object.keys(value[fields[i]]);
if (childFields.length > 0)
{
for (let j = 0; j < childFields.length; j++)
{
if ((value[fields[i]][childFields[j]] + "").indexOf(this.toString()) !== -1)
{
return true;
}
}
}
}
if ((value[fields[i]] + "").indexOf(this.toString()) !== -1)
{
return true;
}
}
}
return false;
}
}


Input Form

<input placeholder="Enter Product Details to Search" class="form-control input-lg" type="text" #searchProduct
(keyup)="0">


Usage

<tr *ngFor="let product of products | search:searchProduct.value;let serial = index">

Answer

String.prototype.toLowerCase() for the win:

compareWithAllFields(value, index)
{
    var fields = Object.keys(value);
    for (let i = 0; i < fields.length; i++)
    {
        if (value[fields[i]] != null)
        {
            if (isObject(value[fields[i]]))
            {
                var childFields = Object.keys(value[fields[i]]);
                if (childFields.length > 0)
                {
                    for (let j = 0; j < childFields.length; j++)
                    {
                        if ((value[fields[i]][childFields[j]] + "").toLowerCase().indexOf(this.toString().toLowerCase()) !== -1)
                        {
                            return true;
                        }
                    }
                }
            }
            if ((value[fields[i]] + "").toLowerCase().indexOf(this.toString().toLowerCase()) !== -1)
            {
                return true;
            }
        }
    }
    return false;
}

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

Comments