How to apply filters to *ngFor?

前端 未结 23 1564
無奈伤痛
無奈伤痛 2020-11-22 03:44

Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still seems to be vague, wit

23条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 04:05

    Another approach I like to use for application specific filters, is to use a custom read-only property on your component which allows you to encapsulate the filtering logic more cleanly than using a custom pipe (IMHO).

    For example, if I want to bind to albumList and filter on searchText:

    searchText: "";
    albumList: Album[] = [];
    
    get filteredAlbumList() {
        if (this.config.searchText && this.config.searchText.length > 1) {
          var lsearchText = this.config.searchText.toLowerCase();
          return this.albumList.filter((a) =>
            a.Title.toLowerCase().includes(lsearchText) ||
            a.Artist.ArtistName.toLowerCase().includes(lsearchText)
          );
        }
        return this.albumList;
    }
    

    To bind in the HTML you can then bind to the read-only property:

    
    
    

    I find for specialized filters that are application specific this works better than a pipe as it keeps the logic related to the filter with the component.

    Pipes work better for globally reusable filters.

提交回复
热议问题