2017-12-27 209 views
-1

我正在制作一个可重复使用的Angular数据表组件,您可以按列进行过滤。现在,我的方法可行,但我担心这不是Angular的最佳做法。是否有另一种方法来过滤单个列,而不是在单击输入时将该特定列添加到“selectColInput”,然后在过滤器管道中使用该列?按自定义角度数据表中的列进行过滤

数据table.component.html

<table> 
    <thead> 
     <tr> 
      <th *ngFor="let col of cols"> 
       {{col.header}} 
       <input type="text" 
       [(ngModel)]=fields[col.value] 
       (click)="selectColInput(col.value)"/> 
      </th> 
     </tr> 
    </thead> 
    <tbody *ngFor="let row of data | filter: fields:selectedInput"> 
     <tr> 
      <td *ngFor="let col of cols">{{row[col.value]}}</td> 
     </tr> 
    </tbody> 
</table> 

数据table.component.ts

import { ColumnsComponent } from './../columns/columns.component'; 
import { Component, Input } from '@angular/core'; 
import { FilterPipe } from './filter.pipe'; 

@Component({ 
    selector: 'app-data-table', 
    templateUrl: './data-table.component.html', 
    styleUrls: ['./data-table.component.css'] 
}) 

export class DataTableComponent { 

    @Input() data 
    cols: ColumnsComponent[] = [] 
    selectedInput: string = '' 
    fields: any = {} 

    selectColInput(col) { 
    this.selectedInput = col 
    } 

    addColumn(column) { 
    this.cols.push(column) 
    } 

} 

filter.pipe.ts

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

@Pipe({ 
    name: 'filter', 
    pure: false 
}) 
export class FilterPipe implements PipeTransform { 

    transform(data: any, fields: any, selectedInput: any): any { 
    if(!data) return; 

    return data.filter(row => { 
     if(row[selectedInput] !== null && row[selectedInput] && fields[selectedInput]){ 
     return row[selectedInput].toLowerCase().includes(fields[selectedInput].toLowerCase()) 
     } 
     return true 
    }) 
    } 

} 

回答

0

可以使用ngModelChange设置过滤器变量没有点击。

(ngModelChange)="selectColInput(col.value)"/> 
相关问题