简体   繁体   中英

Angular ngFor ngIF condition in data filtering by pipe

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM