【问题标题】:How do you implement a search bar to filter a table?您如何实现搜索栏来过滤表格?
【发布时间】:2018-09-24 00:29:33
【问题描述】:

我有一个应用程序表,其中包含两列 - appAcronym 和 appName。大约有 250 行应用程序。我想在表格顶部/标题上实现搜索以按 appAcronym 过滤,以便用户可以快速访问所需的行。

数据如下所示:

export interface App {
appId: number;
appName: string;
appAcronym: string;
}

这是我的申请表

<table class="table table-striped table-hover table-sm" *ngIf="appsList">
        <thead>
            <tr>
                <th scope="col">Acronym</th>
                <th scope="col">System Name</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let app of appsList">
                <td>{{ app.appAcronym }}</td>
                <td>{{ app.appName }}</td>
            </tr>
        </tbody>
    </table>

这是我在实现管道时的尝试

import { Pipe, PipeTransform } from '@angular/core';
import { App } from './components/applevel/applevel.component';
@Pipe({ name: 'searchByAcronym' })

export class SearchByAcronymPipe implements PipeTransform {
transform(appslist: App[], searchText: string, appAcronym: string) {

}

我不熟悉管道,如您所见,我将 transform 的内部留空。管道是完成这项工作的最佳工具吗?如果是这样,你能建议如何让它工作吗?理想的实现是在表的 Acronym 标题上进行搜索。但是外部搜索栏也可以。

【问题讨论】:

    标签: angular html-table pipes-filters


    【解决方案1】:

    您可以克隆此 repo,以获取使用引导列标题进行排序和过滤的示例。 https://github.com/almcaffee/angular-example1

    您不需要管道,管道用于格式化数据。您需要一些过滤,或者您可以每次使用排序/过滤参数进行 api 调用。上面的示例使用静态数据集作为后端服务执行。将它克隆到一个文件夹,npm i,在 localhost 上运行它,看看它的行为,检查代码,看看它在做什么。

    【讨论】:

    • 谢谢,试试这个!
    【解决方案2】:

    我最近为表格实施了过滤器。这是我的解决方案

    管道

    import { Pipe, PipeTransform } from '@angular/core';
    
    
    @Pipe({
      name: 'filter'
    })
    export class FilterPipe implements PipeTransform {
    
      transform(values: any, filterString: string): any {
        if (values.length === 0 || !filterString || filterString.length === 0) {
          return values;
        }
        const resultArray: App[] = [];
        for (const app of values) {
          if ((app.appName && app.appName.includes(filterString))
            || (app.appAcronym && 
                app.appAcronym.includes(filterString))
            
          ) {
            resultArray.push(app);
          }
        }
        return resultArray;
      }
    
    }
    

    用法

     <input placeholder="Search here" [(ngModel)]="textSearch"></input>
    
    <tr *ngFor="let app of appsList" | async | filter:textSearch >
                    <td>{{ app.appAcronym }}</td>
                    <td>{{ app.appName }}</td>
                </tr>
    

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 2017-04-22
      • 1970-01-01
      • 2019-05-10
      • 2018-09-29
      • 1970-01-01
      • 2023-02-25
      • 2012-08-12
      • 1970-01-01
      相关资源
      最近更新 更多