How to apply filters to *ngFor?

How to apply filters to *ngFor?

ngfor filter without pipe
angular 6 ngfor filter by property
angular 7 ngfor filter by property
angular ngfor filter without pipe
angular 2 ngfor filter by property
angular ngfor filter by property
ngfor filter search
ngfor filter object property

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, with no clear documentation.

Namely what I'm trying to achieve could be viewed from the following perspective

<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>

How to implement so using pipes?


Basically, you write a pipe which you can then use in the *ngFor directive.

In your component:

filterargs = {title: 'hello'};
items = [{title: 'hello world'}, {title: 'hello kitty'}, {title: 'foo bar'}];

In your template, you can pass string, number or object to your pipe to use to filter on:

<li *ngFor="let item of items | myfilter:filterargs">

In your pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myfilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], filter: Object): any {
        if (!items || !filter) {
            return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(item => item.title.indexOf(filter.title) !== -1);
    }
}

Remember to register your pipe in app.module.ts; you no longer need to register the pipes in your @Component

import { MyFilterPipe } from './shared/pipes/my-filter.pipe';

@NgModule({
    imports: [
        ..
    ],
    declarations: [
        MyFilterPipe,
    ],
    providers: [
        ..
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Here's a Plunker which demos the use of a custom filter pipe and the built-in slice pipe to limit results.

Please note (as several commentators have pointed out) that there is a reason why there are no built-in filter pipes in Angular.

Angular v4 - Applying filters to *ngFor using pipes, name = 'Angular v4 - Applying filters to *ngFor using pipes'; /** * @type {number} minYear The year of the oldest book in the json. */ minYear: number = 1996  It provides a filter pipe that can filter any list of objects. You basically just specify the property and value {key:value} within your ngFor specification. It's not a lot different from @NateMay's response, except that I explain it in relatively verbose detail.


A lot of you have great approaches, but the goal here is to be generic and defined a array pipe that is extremely reusable across all cases in relationship to *ngFor.

callback.pipe.ts (don't forget to add this to your module's declaration array)

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({
    name: 'callback',
    pure: false
})
export class CallbackPipe implements PipeTransform {
    transform(items: any[], callback: (item: any) => boolean): any {
        if (!items || !callback) {
            return items;
        }
        return items.filter(item => callback(item));
    }
}

Then in your component, you need to implement a method with the following signuature (item: any) => boolean, in my case for example, I called it filterUser, that filters users' age that are greater than 18 years.

Your Component

@Component({
  ....
})
export class UsersComponent {
  filterUser(user: IUser) {
    return !user.age >= 18
  }
}

And last but not least, your html code will look like this:

Your HTML

<li *ngFor="let user of users | callback: filterUser">{{user.name}}</li>

As you can see, this Pipe is fairly generic across all array like items that need to be filter via a callback. In mycase, I found it to be very useful for *ngFor like scenarios.

Hope this helps!!!

codematrix

Angular2: Filtering NgFor Using Pipes - Development, How to filter the content of a table using pipes in Angular2. Using the Pipe in our table component. To use the email filter in our Customers table component we must declare it in the annotation: The pipes: [CustomerEmailFilter], line allows us to use customerEmailFilter in the Customers.html file. We also declare a field email that holds the value for the filter argument.


Simplified way (Used only on small arrays because of performance issues. In large arrays you have to make the filter manually via code):

See: https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

@Pipe({
    name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
    transform(items: any[], field : string, value : string): any[] {  
      if (!items) return [];
      if (!value || value.length == 0) return items;
      return items.filter(it => 
      it[field].toLowerCase().indexOf(value.toLowerCase()) !=-1);
    }
}

Usage:

<li *ngFor="let it of its | filter : 'name' : 'value or variable'">{{it}}</li>

If you use a variable as a second argument, don't use quotes.

Pipes, In fact, you might like to apply them in your HTML templates as you do styles. Add a FlyingHeroesPipe to the *ngFor repeater that filters the list of heroes to just​  < div * ngFor = "let item of itemsList" > < div * ngIf = "conditon(item)" > </ div > </ div > and if you can not use as internal container use ng-container instead. ng-container is useful when you want to conditionally append a group of elements (ie using *ngIf="foo") in your application but don't want to wrap them with another element.


This is what I implemented without using pipe.

component.html
<div *ngFor="let item of filter(itemsList)">
component.ts
@Component({
....
})
export class YourComponent {
  filter(itemList: yourItemType[]): yourItemType[] {
    let result: yourItemType[] = [];
    //your filter logic here
    ...
    ...
    return result;
  }
}

Create a Search Pipe to Dynamically Filter results with Angular 4, Angular JS came with a few built in Filters , such as: A common built in Filter was the template code from the component by adding a file called app.component.​html . *ngFor is Angular's version of Angular JS's ngRepeat. I need to filter items inside an ngFor loop, by changing the category in a drop-down list. Therefore, when a particular category is selected from the list, it should only list the items containing that same category. Also, the drop-down list contains repeated category names. It is necessary for it to list only unique categories (strings).


I'm not sure when it came in but they already made slice pipe that will do that. It's well documented too.

https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

<p *ngFor="let feature of content?.keyFeatures | slice:1:5">
   {{ feature.description }}
</p>

How to apply filters to *ngFor?, Apparently, Angular 2 will use pipes instead of filters as in Angular1 in conjunction with ng-for to filter results, although the implementation still  Preferably you first/instead filter the elements in your component using filter to prevent unnecessary loops when displaying your data: public get singleCategory() { return this.categories.filter((item, index) => index > 2 ) } There is also the option of creating a pipe. (See the linked duplicate)


Creating a Pipe to filter the items in the list using Angular 7, Having a search box & filtering out the list on the basis of the text of that search box is a List of categories --> <ul> <li *ngFor="let item of categories | filter : searchText : 'categoryName'"> {{item. Adding Swagger to ASP. Using ngFor to render an array. This is exactly what ngFor can do for us. All we need to do is to tell the directive, which array to use. Let's say we have a component that we call example-component. This component has a property that is an array. That array could be static and look like the array above or could be filled at runtime.


Angular2: Creating custom search filter pipe for ngFor directive , As you are aware of the fact that, Filters in Angular 1.x have been replaced with pipes in Angular2, unfortunately, search filter for ng-repeat has  With ngFor we can print this data to the screen under the form of a data table, by generating HTML similar to this: What is the syntax of ngFor? To use ngFor, let's create a component so that we can have a working HTML template: This template will generate the HTML table that we showed just above.


angular filter ngfor Code Example, Get code examples like "angular filter ngfor" instantly right from your google search results with the Grepper Chrome Extension. When you use order-by-pipe as the selector it is attempting to find the variables order by and pipe and do who knows what with them. Changing the name: in your pipe to orderByPipe resolves the issue.