Angular ngFor ngIF condition in data filtering by pipe

坚强是说给别人听的谎言 提交于 2021-02-10 07:31:40

问题


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

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

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>

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

回答1:


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>

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>

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.

Here is a working example on StackBlitz.



来源:https://stackoverflow.com/questions/57285679/angular-ngfor-ngif-condition-in-data-filtering-by-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!