Gayathri
Gayathri

Reputation: 85

Unable to do searching using custom pipe created in angular 7

How can i search in angular 7 using pipe (like filter in angular 1) ? Below is the code which i tried.But that returns only if exact match is there. But i need results which contains that word.

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'search',
  pure:true
})
export class SearchPipe implements PipeTransform { 
  transform(data: any,searchTxt:string): any {
    if(!data || !searchTxt)
    {
      return data;
    }   
    return data.filter(function(x) {
      return x.name ==searchTxt}) ;    
   }`
}

i tried below code also but doesn't work

return data.filter(x=>x.name.toString().toLowerCase().indexof(searchTxt.toLowerCase()) !== -1)

This throws error: x.name.indexof is not a function

How can i do contains search using javascript\angular ?

Upvotes: 1

Views: 106

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

You should be using indexOf instead of === or indexof(which I think is a typo in your code).

Plus you should not be using a pipe to filter values. Here's why Angular doesn't recommend using pipes to filter or sort values.

Angular doesn't offer such pipes because they perform poorly and prevent aggressive minification. Both filter and orderBy require parameters that reference object properties. Read more about that here.

That being said, you can basically write the logic to filter data, right inside your Component:

Here, give this a try:

import { Component } from "@angular/core";
import { HttpClient } from "@angular/common/http";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  users = [];
  filteredUsers = [];

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .get("https://jsonplaceholder.typicode.com/users")
      .subscribe((users: any[]) => {
        this.users = users;
        this.filteredUsers = [...this.users];
      });
  }

  onSearchTextChange(searchString) {
    this.filteredUsers = [
      ...this.users.filter(user => user.name.indexOf(searchString) > -1)
    ];
  }
}

Here's a Working CodeSandbox Sample for your ref.

Upvotes: 1

Related Questions