Angular 2+ - check if Pipe returns an empty subset of original list

前端 未结 7 1351
天涯浪人
天涯浪人 2021-02-04 02:37

I have a list of strings that I want to iterate through, but I want to be able to filter them using a search term. Like this:

相关标签:
7条回答
  • 2021-02-04 03:21

    This is the cleanest solution I've been able to produce.

    @Pipe({
      name: 'search'
    })
    export class SearchPipe {
    
      transform(value, searchTerm) {
        let result = ...
        if(result.length === 0) {
          return [undefined];
        }
        return result;
      }
    }
    

    By returning [undefined], checks in the DOM are much cleaner and easier to read.

    <ng-container *ngFor="let item of list | search: searchTerm">
      <div *ngIf="!item">"No matches"</div>
      <div *ngIf="item">{{ item }}</div>
    </ng-container>
    
    0 讨论(0)
提交回复
热议问题