【问题标题】:How to show the list of data at the time of search operation?搜索操作时如何显示数据列表?
【发布时间】:2019-04-24 07:06:39
【问题描述】:
我需要在搜索操作时显示数据列表。默认情况下,列表将为空。如果发生任何搜索,相应的数据将显示在网格中。如果未发生搜索,则列表将为空。如何使用 Angular 6 来实现这一点。获取我正在使用 *ngFor 的数据列表。默认情况下,它显示列表中的所有数据。但在我的场景中,数据显示在搜索时。
serach: <input type="text" [(ngModel)]="queryString">
<table>
<thead>
<tr>
<th>first Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of data | filter:queryString:'firstname'; let i = index">
<td>{{item.firstname}}</td>
</tr>
</tbody>
</table>
【问题讨论】:
标签:
javascript
html
css
angular
ruby-on-rails-4
【解决方案1】:
你必须创建一个过滤器
import { Injectable, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'searchfilter'
})
@Injectable()
export class SearchFilterPipe implements PipeTransform {
transform(items: any[], searchInTable: any): any[] {
if (searchInTable === undefined) {
return null;
}
return items.filter(function(x) {
var add = x.firstname.toLowerCase().includes(searchInTable.toLowerCase());
return (add);
});
}
}
在 HTML 中
serach: <input type="text" [(ngModel)]="searchInTable">
<table>
<thead>
<tr>
<th>first Name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of data | searchfilter:searchInTable; let i = index">
<td>{{item.firstname}}</td>
</tr>
</tbody>
</table>
在 app.module 中
import { SearchFilterPipe } from '../shared/filters';
declarations: [HomeComponent, SearchFilterPipe],
【解决方案2】:
在您的filter 组件中,根据返回的项目检查queryString 长度。如下所示。如果长度为0,则返回空数组
if ( !queryString || queryString.length==0) return [];
【解决方案3】:
尝试使用 NgIf 有条件地隐藏 DOM 元素。
给表格元素赋予 NgIf 条件,检查输入搜索字段的 ngmodel 长度。
serach: <input type="text" [(ngModel)]="queryString">
<table *ngIf="queryString.length !=0">
</table>