angular - 使用角度过滤管的基于列的搜索
问题描述
根据我在特定列中键入的文本,仅需要搜索该列。
我面临的问题是:当我输入一列时,其他列中也会出现相同的文本。为了解决这个问题,我使用了以下代码:
<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);
}
解决方案
不要在元素上使用过滤器管道,而是<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);
}
希望能帮助到你。
推荐阅读
- android - 如何在 TextView 左侧用项目符号绘制每个 TextView 的尖边框
- dart - AngularDart 与 Redux
- java - Android studio,从类中插入的类的变量继承
- tensorflow - 我应该自己初始化变量还是只通过 global_variable_initialize() 初始化?
- c - C 的小数部分是 3.9999999,为什么不是 4?
- matlab - 如何在 MATLAB 中访问图像的特定块?(不是裁剪)
- javascript - 如何在 TypeScript 中通用地键入变量绑定?
- r - R函数:无法从函数调用数据帧
- r - RDCOMClient - 设置垂直范围值
- r - 在 ggplot2 上覆盖 ggmap 、 geom_polygon(shape file)