如何使用 angular 4 在 table 中搜索基于索引的值?

How to search index based values in table using angular 4?

我正在使用 angular 4,我使用的数组包含我需要根据索引搜索的值列表。我收到错误...如何搜索基于索引的值?

ang.html:

<div class="col-md-6" >
 <input type="text" [(ngModel)]="searchText"  class="form-control" placeholder="Search By Category" />
            </div>
<table class="table table-striped table-bordered table-responsive full-data-table">
    <thead>
    <tr><th S.No</th>
     <th>sName</th>
     <th>cName</th>
    </thead>
   <tbody>
            <tr *ngFor="let item of data | category: searchText">
            <td>{{item[0]}}</td>
            <td>{{item[1]}}</td>
            <td>{{item[2]}}</td>
   </tbody>

pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'category' })
export class CategoryPipe implements PipeTransform {
  transform(categories: any, searchText: any): any {
    if(searchText == null) return categories;

    return categories.filter(function(category){
      return category.toLowerCase.indexOf(searchText.toLowerCase() != -1);
    })
  }
}

错误:

ERROR TypeError: Cannot read property 'indexOf' of undefined

值:

[["Chrocin","paracetamal","combination name",200,10,18,"tablet",22,1],["Phar","chw","combination name",200,6,18,"tablet",3,2]]

您不能对子数组执行 toLowerCase() 操作。您的代码是这样做的:

[].toLowerCase()

您需要遍历数组的子数组。而且您不能将 toLowerCase() 数字转换为字符串。像这样:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'category' })
export class CategoryPipe implements PipeTransform {
  transform(categories: any, searchText: any): any {
    if(searchText == null) return categories;

    //categories are [[]]
    return categories.filter(function(category){

      //category is []
      return category.filter(function(subCategory) {

        //subCategory is string that we compare with searchText
        return subCategory.toString().toLowerCase() == searchText.toLowerCase();
      });
    })
  }
}

如果你想通过子数组中的任何字段进行搜索,那么你可以这样做:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'category' })
export class CategoryPipe implements PipeTransform {
  transform(categories: any, searchText: any): any {
    if(searchText == null || searchText == '') {
      return categories;
    } else {
      let filteredCategories = [];
      categories.filter(function(category){
        category.filter(function(subCategory) {
          if(subCategory.toString().toLowerCase() == searchText.toLowerCase()) {
            filteredCategories.push(category);
          }
        });
      });
      return filteredCategories;
    }
  }
}

这是一个例子: https://stackblitz.com/edit/search-pipe