Angular 2表搜索管道过滤器无法正常工作

时间:2017-01-24 12:38:23

标签: angular angular2-pipe

我正在Angular 2中创建一个表组件,我正在创建一个公用表搜索过滤器管道,它正常工作但不在相应的列中显示值。 当我开始在文本框中键入搜索键时,过滤后的值会正确显示,但不会显示在相应的列下。 很抱歉,如果这个问题是重复的,我已经花了足够的时间搜索网页,但我无法获得解决方案。

以下是供您参考的代码

component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public tableData: any = [
     {"Name":"Gaurav","Address":"Chennai","Contact":"9632587410"},
     {"Name":"Rakesh","Address":"Goa","Contact":"852397410"}
  ];
}

Pipe.ts

@Pipe({
  name: 'searchPipe'
})
export class searchPipe implements PipeTransform {
   transform(value: any, args: string[]): any {
      let filter = args[0];

      if (filter && Array.isArray(value)) {
         let filterKeys = Object.keys(filter);
         return value.filter(item =>
            filterKeys.reduce((key, keyName) =>
               key && item[keyName].toUpperCase() === filter[keyName].toUpperCase(), true));
      } else {
         return value;
      }
   }
}

component.html

<input type="text" #searchFilter (keyup)="0"/>
<table>
  <tr>
    <th *ngFor="let colValues of tableData | columnPipe">{{colValues}}</th>
  </tr>
  <tr *ngFor="let row of tableData">
    <td *ngFor="let rowValues of row | rowPipe |searchPipe:searchFilter.value">{{rowValues}}</td>
  </tr>
</table>

全面工作Plunker,帮助我解决问题

1 个答案:

答案 0 :(得分:5)

我想你想要这样:https://plnkr.co/edit/olkIEiOc67Ld28NuASef?p=preview

你不想&#34;隐藏&#34;整个td,而你只是想&#34;隐藏&#34;价值..

@Pipe({
  name: 'searchPipe'
})
export class searchPipe implements PipeTransform {
  transform(value: any, args: string[]): any {
    let filter = args[0];

    if (filter && Array.isArray(value)) {
      let filterKeys = Object.keys(filter);
      return value.filter(item => filterKeys.reduce((key, keyName) => key && item[keyName].toUpperCase() === filter[keyName].toUpperCase(), true));
    }
    // new case !
    else if (filter && typeof value === 'string') {
      return value.toUpperCase().indexOf(filter.toUpperCase()) >= 0 ? value : '';
    }
    else {
      return value;
    }
  }
}
<td *ngFor="let rowValues of row | rowPipe">{{ rowValues | searchPipe : searchFilter.value }}</td>

<强>更新

要显示整行,您必须过滤tableData

像这样更改管道:

@Pipe({
  name: 'searchPipe'
})
export class searchPipe implements PipeTransform {
  transform(values: any[], filter: string): any {
    if (!values || !values.length) return [];
    if (!filter) return values;

    filter = filter.toUpperCase();

    if (filter && Array.isArray(values)) {
      const keys = Object.keys(values[0]);
      return values.filter(v => v && keys.some(k => v[k].toUpperCase().indexOf(filter) >= 0));
    }
  }
}
<tr *ngFor="let row of tableData | searchPipe : searchFilter.value">
  <td *ngFor="let rowValues of row | rowPipe">{{ rowValues }}</td>
</tr>

现场演示:https://plnkr.co/edit/jXfqfCuJpKdw9HtL569T?p=preview