管道数据过滤中的Angular ngFor ngIF条件 [英] Angular ngFor ngIF condition in data filtering by pipe

查看:79
本文介绍了管道数据过滤中的Angular ngFor ngIF条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ngFor 基于使用管道的搜索过滤 - 这工作正常,

ngFor filtering based on a search using pipe - This is working fine ,

现在我必须根据搜索查询添加 ngIf 条件

Now I have to add ngIf condition based on the search query

如果没有结果,那么我必须显示另一个带有无数据"文本的新 div

If nothing result then I have to show another new div with 'no data' text

<input type="text" [(ngModel)]="queryString" placeholder="Search to type">

<li *ngFor="let project of projects | FilterPipe: queryString ;>
{{project.project_name}} 
</li>

//管道

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;
  }

推荐答案

要在模板中使用filter管道的结果,可以借助创建一个局部变量as 关键字.

To use the results of the filter pipe in the template, you can create a local variable with the help of the as keyword.

<li *ngFor="let project of (projects | FilterPipe: queryString) as results">
  {{project.project_name}} 
</li>

现在您可以在 results 变量中访问来自过滤器管道的结果.但是这个局部变量的范围现在仅限于托管 HTML 元素及其子元素.我们可以通过稍微重写您的代码来解决这个问题.

Now you can access the results from your filter pipe in the results variable. But the scope of this local variable is now limited to the hosting HTML element and its children. 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>

通过这种方式,我们扩展了 results 变量的范围,当过滤的数据集为空时,我们可以轻松地使用它来显示 No Data.

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.

这是一个关于 StackBlitz 的工作示例.

Here is a working example on StackBlitz.

这篇关于管道数据过滤中的Angular ngFor ngIF条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆