首页 > 解决方案 > 使用角度过滤管的基于列的搜索

问题描述

下面是我的表格视图。每列都有搜索

根据我在特定列中键入的文本,仅需要搜索该列。

我面临的问题是:当我输入一列时,其他列中也会出现相同的文本。为了解决这个问题,我使用了以下代码:

        <tr>
            <th *ngFor="let head of headElements; let i = index" scope="col">
                <h5 class="text-color">{{head}}</h5>
                <div class="md-form mb-0">
                    <input [(ngModel)]="searchText[i]" type="text" class="form-control" 
                      id="search_{{i}}" mdbInput />
                    <label for="search_{{i}}">Search</label>
                </div>
            </th>
        </tr>

通过给[(ngModel)]="searchText[i]"[(ngModel)]="searchText[head]"我可以在不同的输入框中键入不同的文本。

我无法获取在过滤器中输入的文本:searchText;

下面是我查看表格数据的代码

    <tbody>
        <tr *ngFor="let el of elements | filter : searchText; let i = index" mdbWavesEffect>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex"
                scope="row">{{el.firstName}} {{el.middleName}} {{el.lastName}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.mobileNumber}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.joiningYear}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.emailId}}</td>
            <td class="p-2" *ngIf="i+1 >= mdbTablePagination.firstItemIndex && i < mdbTablePagination.lastItemIndex">
                {{el.designation}}</td>
        </tr>
    </tbody>

接下来我searchText: any = [];在 conponent.ts 文件中声明,否则它给出错误未定义

最后是我的过滤管道代码

  if (!employees || !searchTerm) {
    return employees;
  }
  return employees.filter(employee =>
    employee.mobileNumber.toLowerCase().indexOf(searchTerm) !== -1);

}

标签: angulartypescriptfilterpipeangular7

解决方案


不要在元素上使用过滤器管道,而是<tr>尝试监听元素上的更改事件<input>

<tr>
        <th *ngFor="let head of headElements; let i = index" scope="col">
            <h5 class="text-color">{{head}}</h5>
            <div class="md-form mb-0">
                <input [(ngModel)]="searchText[i]" (change)="filterElements(searchText[i])" type="text" class="form-control" 
                  id="search_{{i}}" mdbInput />
                <label for="search_{{i}}">Search</label>
            </div>
        </th>
    </tr>

在组件类中:

private elementsCopy = Object.assign({}, this.elements);
public filterElements(searchTerm){
    if (!this.elementsCopy || !searchTerm) {
        return this.elementsCopy ;
      }
  return this.elementsCopy.filter(employee =>
    employee.mobileNumber.toLowerCase().indexOf(searchTerm) !== -1);

}

希望能帮助到你。


推荐阅读