Bhrungarajni
Bhrungarajni

Reputation: 2535

How to filter the data from the list of items based on input typed irrespective of case sensitive using angular2

I have a search box, where i type in the input field, and the filter works if i give full word with case sensitive. Can anyone help to filter the list of items based on input typed letter by letter.

HTMl:

<mat-tab label="Active">
  <mat-icon for="search">search</mat-icon>
  <input type="search" [(ngModel)]="filter" name="search" class="search" placeholder="Company">
  <ul>
    <li *ngFor="let message of activeMessages| messagefilter: filter" (click)="showMessage(message)" [class.activeShow]="message.id == message_id">
      <span>{{message.messages[message.messages.length -1].updated_at | date:'dd.MM.yyyy'}}</span>
      <img style="width: 40px;" [src]="message.from_user_image || '../assets/images/msg.png'"/>
      <p style="padding-top: 16px;display: inline;">{{message.from_user_name}}</p>
      <p style="padding-top: 10px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"><b>{{message.messages[message.messages.length -1].text}}</b></p>
    </li>
  </ul>
</mat-tab>

pipe.ts:

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

@Pipe({
  name: 'messagefilter',
  pure: false
})

export class MessagePipe implements PipeTransform {
  transform(items, filter) {
    if (!items || !filter) {
      return items;
    }
    return items.filter((item) => this.applyFilter(item, filter));
  }
  /* Function to apply filter for Messages */
    applyFilter(user, filter): boolean { 
     console.log(user.from_user_name.indexOf(filter))
     console.log(filter) 
     console.log(user.from_user_name)
   if (user.from_user_name.indexOf(filter) > -1) { 
      return true; 
    } else{ 
      return false; 
   } 
  }
}

Upvotes: 0

Views: 44

Answers (1)

Sravan
Sravan

Reputation: 18647

You can use toLowerCase in the filter to check.

The code user.from_user_name.indexOf(filter) > -1 will not check the case sensitivity so you should change that to, user.from_user_name.toLowerCase().indexOf(filter.toLowerCase()) > -1

Your pipe:

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

@Pipe({
  name: 'messagefilter',
  pure: false
})

export class MessagePipe implements PipeTransform {
  transform(items, filter) {
    if (!items || !filter) {
      return items;
    }
    return items.filter((item) => this.applyFilter(item, filter));
  }
  /* Function to apply filter for Messages */
    applyFilter(user, filter): boolean { 
   if (user.from_user_name.toLowerCase().indexOf(filter.toLowerCase()) > -1) { 
      return true; 
    } else{ 
      return false; 
   } 
  }
}

Upvotes: 1

Related Questions