【问题标题】:Filtering by column in custom Angular data table按自定义 Angular 数据表中的列过滤
【发布时间】:2026-02-15 11:55:01
【问题描述】:

我正在制作一个可重用的 Angular 数据表组件,您可以在其中按列过滤。现在,我的方法有效,但我担心这不是 Angular 的最佳实践。除了在单击输入时将该特定列添加到“selectColInput”,然后在过滤器管道中使用它之外,还有另一种过滤单个列的方法吗?

数据表.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>

data-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
    })
  }

}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您无需点击即可使用ngModelChange 设置过滤器变量。

    (ngModelChange)="selectColInput(col.value)"/>
    

    【讨论】: