[英]Angular ngFor ngIF condition in data filtering by pipe
ngFor filtering based on a search using pipe - This is working fine , ngFor 基于使用管道的搜索进行过滤 - 这工作正常,
Now I have to add ngIf condition based on the search query现在我必须根据搜索查询添加 ngIf 条件
If nothing result then I have to show another new div with 'no data' text如果没有结果,那么我必须显示另一个带有“无数据”文本的新 div
<input type="text" [(ngModel)]="queryString" placeholder="Search to type">
<li *ngFor="let project of projects | FilterPipe: queryString ;>
{{project.project_name}}
</li>
//pipe //管道
transform(value: any, input:any ): any {
if(input){
input = input.toLowerCase();
return value.filter(function (el: any) {
return el.project_name.toLowerCase().indexOf(input) > -1;
})
}
return value;
}
To use the results of the filter
pipe in the template, you can create a local variable with the help of the as
keyword.要在模板中使用
filter
管道的结果,您可以在as
关键字的帮助下创建一个局部变量。
<li *ngFor="let project of (projects | FilterPipe: queryString) as results">
{{project.project_name}}
</li>
Now you can access the results from your filter pipe in the results
variable.现在,您可以在
results
变量中访问来自过滤器管道的results
。 But the scope of this local variable is now limited to the hosting HTML element and its children.但是这个局部变量的范围现在仅限于托管 HTML 元素及其子元素。 We can fix this by rewriting your code a little.
我们可以通过稍微重写您的代码来解决这个问题。
<ul *ngIf="(projects | FilterPipe: searchQuery) as results">
<li *ngFor="let project of results">
{{project.project_name}}
</li>
<span *ngIf="results.length === 0">No data</span>
</ul>
This way we have expanded the scope of the results
variable and we can easily use it to display No Data
when the filtered dataset is empty.通过这种方式,我们扩大了
results
变量的范围,当过滤后的数据集为空时,我们可以轻松地使用它来显示No Data
。
Here is a working example on StackBlitz .这是StackBlitz上的一个工作示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.