How make filter in ngx-pagination - javascript

In Angular 7 + Electron 4 I use ngx-pagination but can't resolve problem with filter. I make as in a documentation, but I get error Uncaught Error: Template parse errors:
The pipe 'stringFilter' could not be found
Help me please. Thanks in advance
Html-1:
<input
type="text"
name="search"
class="search__input"
placeholder="Search by Name..."
[(ngModel)]="tableService.filter">
Html-2:
<ul class="table-body__list">
<li *ngFor="let item of tableService.items | stringFilter: tableService.filter | paginate: config">
<app-item [item]="item"></app-item>
</li>
</ul>
<pagination-controls
[maxSize]="maxSize"
directionLinks="true"
responsive="true"
previousLabel="Previous page"
nextLabel="Next page"
(pageChange)="onPageChange($event)">
</pagination-controls>
TypeScript:
import { Component, OnInit } from '#angular/core';
import { PaginationInstance } from 'ngx-pagination';
import { TableService } from '../../services/table.service';
#Component({
selector: 'app-jobs-table',
templateUrl: './jobs-table.component.html',
styleUrls: ['./jobs-table.component.scss']
})
export class JobsTableComponent implements OnInit {
filter = '';
maxSize = 9;
config: PaginationInstance = {
itemsPerPage: 11,
currentPage: 1
};
constructor(public tableService: TableService) { }
ngOnInit() {
}
onPageChange(number: number) {
this.config.currentPage = number;
}
}
In TableService:
filter = '';

As found on github (search on filter in the repository). apparently npx-pagination doesn't come with any standard filter pipes. their doc is .... sub-optimal
import {Pipe} from "#angular/core";
/**
* A simple string filter, since Angular does not yet have a filter pipe built in.
*/
#Pipe({
name: 'stringFilter'
})
export class StringFilterPipe {
transform(value: string[], q: string) {
if (!q || q === '') {
return value;
}
return value.filter(item => -1 < item.toLowerCase().indexOf(q.toLowerCase()));
}
}
Funny comment btw: Angular removed pipes for filtering because of performance reasons.

you ca only change stringFilter with filter .
<ul class="table-body__list">
<li *ngFor="let item of tableService.items | filter: tableService.filter | paginate: config">
<app-item [item]="item"></app-item>
</li>
</ul>

Related

Can't bind to 'ngForFor' since it isn't a known property of 'ion-item' [duplicate]

This question already has answers here:
Can't bind to 'ngForFor' since it isn't a known property of 'li'
(2 answers)
Closed 4 months ago.
I'm trying to display data from an API here, but I get the error "" in the console output (see picture)
My problem is that I don't know exactly why I get the error and what I can do about it, I've already tried it without * and also with a different notation. The CommonModuels and NgModuels modules are also imported into both the API service and thets.
<ion-list>
<ion-list-header>
Stundet List
</ion-list-header>
<ion-item lines="insert" *ngFor="let student for students">
<ion-label>
<p> {{ students.studentsOne }} </p>
</ion-label>
</ion-item>
</ion-list>
import { Component } from '#angular/core';
import { ApiService } from '../api.service';
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
imports: [CommonModule, NgModule]
})
export class HomePage {
year: any;
studentOne: any;
studentTwo: any;
student: any[] = [];
constructor(public _apiService: ApiService)
{
this.getStudents()
}
addStudent(){
let data = {
year: this.year,
studentOne: this.studentOne,
studentTwo: this.studentTwo,
}
this._apiService.addStudent(data).subscribe((res:any) => {
console.log("SUCCESS ===",res);
this.year = '';
this.studentOne = '';
this.studentTwo = '';
alert('SUCCESS')
this.getStudents()
},(error: any) => {
console.log("ERROR ===",error);
alert('ERROR');
})
}
getStudents(){
this._apiService.getStudents().subscribe((res:any) => {
console.log("SUCCESS ===",res);
this.student = res;
},(error: any) => {
console.log("ERROR ===",error);
})
}
}
Fix <ion-item lines="insert" *ngFor="let student for students"> to <ion-item lines="insert" *ngFor="let student of students"> (of instead of for)

Can we data inject the array and single data of the array

I am actually trying to inject the array and the data inside the array to another component but is constantly getting errors.
My list.component.ts
Here i injected the itemList array from app.component and this component is working just fine. No errors here.
import { Component, OnInit, Input, Output, EventEmitter } from '#angular/core';
import {List} from './list.model'
#Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
#Input() itemList: List[] = [];
#Output() onItemSelected: EventEmitter<List>;
private currentItem: List;
constructor(){
this.onItemSelected = new EventEmitter();
}
onClick(list: List): void {
this.currentItem = list;
this.onItemSelected.emit(list);
console.log(`clicking list title: ${list.title}`);
}
isSelected(list: List): boolean {
if (!list || !this.currentItem) {
return false;
}
return list.title === this.currentItem.title;
}
ngOnInit() {
}
}
list.component.html
Here i try to inject both the array and then using ngFor i try to inject the single list also.
<div class="ui grid posts">
<app-list-row
[lists]="itemList"
*ngFor="let list of itemList"
[list]="list"
(click)='onClick(list)'
[class.selected]="isSelected(list)">
</app-list-row>
</div>
list-row.component.ts
I am mainly trying to input the array in this component so that i can use the splice method to delete my list. I tried the delete list;method but this says i cannot use delete in strict mode. Therefore i am trying to input the array and use the splice method.
import { Component, OnInit, Input} from '#angular/core';
import {List} from '.././list/list.model';
#Component({
selector: 'app-list-row',
inputs: ['list: List'],
templateUrl: './list-row.component.html',
styleUrls: ['./list-row.component.css'],
host: {'class': 'row'},
})
export class ListRowComponent implements OnInit {
list: List;
#Input() lists: List[];
deletelist(list: List): void {
let index: number = this.lists.indexOf(list);
if (index !== -1) {
this.lists.splice(index, 1);
}
}
ngOnInit() {
}
}
list-row.component.html
In this write a div and use a lable of delete icon and give an event of click with the "deleteList(list)".
<div class="Eight wide column left aligned title">
<div class="value">
<div class = "hello">
<b>
{{ list.title | uppercase }}
</b>
<div style="float: right;" class="ui label">
<i class="delete icon"
(click)="deleteList(list)"
></i>
</div>
</div>
</div>
</div>
These are my codes and i dont know whether i can do the dependency injection of both the array and its single data in the array. If i can, what ways are there to do it. while running in server the console error is
Unhandled Promise rejection: Template parse errors:
Can't bind to 'list' since it isn't a known property of 'app-list-row'.
1. If 'app-list-row' is an Angular component and it has 'list' input, then verify that it is part of this module.
2. If 'app-list-row' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message.
("
[lists]="itemList"
*ngFor="let list of itemList"
[ERROR ->][list]="list"
(click)='onClick(list)'
[class.selected]="isSelected(list)">
"): ListComponent#4:2 ; Zone: <root> ; Task: Promise.then ; Value: SyntaxError {__zone_symbol__error: Error: Template parse errors:
Can't bind to 'list' since it isn't a known property of 'app-list-row'…, _nativeError: ZoneAwareError, __zone_symbol__currentTask: ZoneTask, __zone_symbol__stack: "Error: Template parse errors:↵Can't bind to 'list'…ttp://localhost:4200/polyfills.bundle.js:6060:47)", __zone_symbol__message: "Template parse errors:↵Can't bind to 'list' since …lected]="isSelected(list)">↵"): ListComponent#4:2"} Error: Template parse errors:
Can't bind to 'list' since it isn't a known property of 'app-list-row'.
1. If 'app-list-row' is an Angular component and it has 'list' input, then verify that it is part of this module.
2. If 'app-list-row' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message.
("
[lists]="itemList"
*ngFor="let list of itemList"
[ERROR ->][list]="list"
(click)='onClick(list)'
[class.selected]="isSelected(list)">
Thank you.
Add #Input() to list variable in ListRowComponent class and check if it is working or not and remove inputs from metadata.
import { Component, OnInit, Input} from '#angular/core';
import {List} from '.././list/list.model';
#Component({
selector: 'app-list-row',
templateUrl: './list-row.component.html',
styleUrls: ['./list-row.component.css'],
host: {'class': 'row'},
})
export class ListRowComponent implements OnInit {
#Input() list: List;
#Input() lists: List[];
deletelist(list: List): void {
let index: number = this.lists.indexOf(list);
if (index !== -1) {
this.lists.splice(index, 1);
}
}
ngOnInit() {
}
}
or
Remove :List from inputs as
import { Component, OnInit, Input} from '#angular/core';
import {List} from '.././list/list.model';
#Component({
selector: 'app-list-row',
templateUrl: './list-row.component.html',
inputs :['list']
styleUrls: ['./list-row.component.css'],
host: {'class': 'row'},
})
export class ListRowComponent implements OnInit {
list: List;
#Input() lists: List[];
deletelist(list: List): void {
let index: number = this.lists.indexOf(list);
if (index !== -1) {
this.lists.splice(index, 1);
}
}
ngOnInit() {
}
}
I got the answer. I did not do two input bindings but i created a custom event in the list-row.component and emmited the list to list.Component.
import { Component, Input, Output, EventEmitter} from '#angular/core';
import {List} from '.././list/list.model';
#Component({
selector: 'app-list-row',
templateUrl: './list-row.component.html',
styleUrls: ['./list-row.component.css'],
host: {
'class': 'row'
}
})
export class ListRowComponent {
#Input() list: List;
#Output() deleted = new EventEmitter<List>();
deletedl() {
const listing: List = this.list;
this.deleted.emit(listing);
}
In the template I used the click event to call the deletel() method.
<div class="Eight wide column left aligned title">
<div class="value">
<div class = "hello">
<b>
{{ list.title | uppercase }}
</b>
<div style="float: right;" class="ui label">
<i class="delete icon"
(click)="deletedl()">
</i>
</div>
</div>
</div>
</div>
Then I just called the event in the list.component
list.component.html
<div class="ui grid posts">
<app-list-row
*ngFor="let list of itemList"
[list]="list"
(click)='onClick(list)'
[class.selected]="isSelected(list)"
(deleted)="deletedl($event)">
</app-list-row>
</div>
Then i called a method in list.component to delete the list from the array using Splice method.
list.component
import { Component, Input} from '#angular/core';
import {List} from './list.model';
#Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent {
#Input() itemList: List[] = [];
private currentItem: List;
onClick(list: List): void {
this.currentItem = list;
console.log(`clicking list title: ${list.title}`);
}
isSelected(list: List): boolean {
if (!list || !this.currentItem) {
return false;
}
return list.title === this.currentItem.title;
}
deletedl(list: List) {
console.log(`deleting list title: ${list.title}`);
let index: number = this.itemList.indexOf(list);
if (index !== -1) {
this.itemList.splice(index, 1);
}
}
}
I have learned that if we want to get some input from the parent component than using property binding helps and when we want to run some output from our parent component then event binding is helpful.

Sharing and filtering a value between components in angular2

I have a component that pulls in a value posts like so:
import { Component, OnInit} from "#angular/core";
import template from "./event.component.html";
import style from "./event.component.scss";
#Component({
selector: "EventComponent",
template,
styles: [ style ]
})
export class EventComponent implements OnInit {
posts = [];
constructor() {}
ngOnInit() {
this.posts = {'test': 0,'test': 1};
}
}
This is then looped over in a html template like so AND injected into another component in this case called "mapCompenent" it is also filter in the html using a pipe:
loop 'EventComponent' content
<input id="search_events" type="text" name="search_events" [(ngModel)]="search" ngDefaultControl/>
<mapCompenent [(posts)]="posts"></mapCompenent>
<div class="col s6 m6 l4 cards-container" *ngFor="let post of posts | searchPipe:'name':search "></div>
filter
import { Pipe, PipeTransform, Input, ChangeDetectorRef } from '#angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '#angular/forms';
#Pipe({
name : 'searchPipe',
pure: false,
})
export class SearchPipe implements PipeTransform {
public transform(value, key: string, term: string) {
if(term === '' || typeof term === undefined ){
return value;
}
return value.filter((item) => {
if (item.hasOwnProperty(key)) {
if (term) {
let regExp = new RegExp('\\b' + term, 'gi');
//this.ref.markForCheck();
return regExp.test(item[key]);
} else {
return true;
}
} else {
return false;
}
});
}
}
mapComponent
import { Component, OnInit, Input, OnChanges, SimpleChanges, SimpleChange } from "#angular/core";
import template from "./map.component.html";
import style from "./map.component.scss";
#Component({
selector: 'mapCompenent',
styles: [ style ],
template
})
export class MapComponent implements OnInit, OnChanges{
#Input() posts: object = {};
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges) {
const posts: SimpleChange = changes.posts;
console.log('prev value: ', posts.previousValue);
console.log('got posts: ', posts.currentValue);
}
}
As soon as the page is loaded the mapcomponent grabs the ngOnChanges BUT not when the filter is used to filter the posts, the loop updates the posts fine and the filter works there the problem is the mapcomponent. What is the best way to notify the mapcomponent of a change to the posts Object?
The pipe will not overwrite the original posts property in EventComponent, so you are only using the filtered version in the *ngFor:
<input id="search_events" type="text" name="search_events" [(ngModel)]="search" ngDefaultControl/>
<mapCompenent [(posts)]="posts"></mapCompenent>
<div class="col s6 m6 l4 cards-container" *ngFor="let post of posts | searchPipe:'name':search "></div>
One solution is to add the pipe to the <mapComponent>'s posts attribute as well, but note it can't be two-way binded ([()]) then, you should change it to one-way ([]).
<input id="search_events" type="text" name="search_events" [(ngModel)]="search" ngDefaultControl/>
<mapCompenent [posts]="posts | searchPipe:'name':search"></mapCompenent>
<div class="col s6 m6 l4 cards-container" *ngFor="let post of posts | searchPipe:'name':search"></div>
A better solution would be to inject that pipe into the EventComponent constructor, listen for changes on the search input or watching search and update another attribute, let's say filteredPosts accordingly using the pipe, and use that one both in the *ngFor and the <mapCompenent>:
#Component({ ... })
export class EventComponent implements OnInit {
posts = [];
filteredPosts = [];
constructor(private searchPipe: SearchPipe) {}
ngOnInit() {
this.posts = ...;
this.form.search.valueChanges.subscribe((value) => {
this.filteredPosts = this.searchPipe.transform(this.posts, 'name', value);
});
}
}

Invalid argument for pipe 'AsyncPipe'

So i get this when i try to get my data from firebase
Invalid argument '{"-KCO4lKzEJPRq0QgkfHO":{"description":"teste","id":1457488598401,"resourceUrl":"tete","title":"test2"}}' for pipe 'AsyncPipe' in [listItems | async in ArcListComponent#2:10]
ArcListComponent
import { Component, OnInit } from "angular2/core";
import { FirebaseService } from "../shared/firebase.service";
import { ArcItem } from "./arc-item.model";
#Component({
selector: "arc-list",
template: `
<ul class="arc-list">
<li *ngFor="#item of listItems | async " class="arc-item">
<h3>{{ item.name}}</h3><a [href]="item.resourceUrl" target="_blank" class="btn btn-success pull-right"><span>Go</span></a>
<hr>
<blockquote>{{ item.description }}</blockquote>
<hr>
</li>
</ul>
`
})
export class ArcListComponent implements OnInit {
listItems: string;
constructor(private _firebaseService: FirebaseService) {}
ngOnInit(): any {
this._firebaseService.getResources().subscribe(
resource => this.listItems = JSON.stringify(resource),
error => console.log(error)
);
}
}
firebase_service
import { Injectable } from "angular2/core";
import { Http } from "angular2/http";
import "rxjs/Rx";
#Injectable()
export class FirebaseService {
constructor(private _http: Http) {}
setResource(id: number, title: string, description: string, resourceUrl: string) {
const body = JSON.stringify({ id: id, title: title, description: description, resourceUrl: resourceUrl});
return this._http
.post("https://######.firebaseio.com/resource.json", body)
.map(response => response.json());
}
getResources() {
return this._http
.get("https://######.firebaseio.com/resource.json")
.map(response => response.json());
}
}
I know i am trying to show my data the wrong way but i do not know how to fix this. any help appreciated.
The async pipe expects an observable or a promise. http.get and map operator return observable, so you can set the returned object into the listItems property of your component. You don't need to subscribe in this case:
this.listItems = this._firebaseService.getResources();
Moreover the object, this element will "receive" must be an array to be able to use it within an ngFor. You service returns an object and not an array from Firebase. If you want to iterate over the keys of the object, you need to implement a custom pipe:
#Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]);
}
return keys;
}
}
and use it like this:
#Component({
selector: "arc-list",
template: `
<ul class="arc-list">
<li *ngFor="#item of listItems | async | keys" class="arc-item">
<h3>{{ item.value.name}}</h3><a [href]="item.value.resourceUrl" target="_blank" class="btn btn-success pull-right"><span>Go</span></a>
<hr>
<blockquote>{{ item.value.description }}</blockquote>
<hr>
</li>
</ul>
`,
pipes: [ KeysPipe ]
})
See this question for more details:
How to display json object using *ngFor
async pipe works with observables and/or promises. It does subscription for you, so you just have to pass an observable without subscribing to it in your code:
ngOnInit(): any {
this.listItems = this._firebaseService.getResources()
}

Angular2 Pipe - How can I do a basic string filter on a list of items? [duplicate]

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.
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 my case, I found it to be very useful for *ngFor like scenarios.
Hope this helps!!!
codematrix
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.
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;
}
}
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>
A simple solution that works with Angular 6 for filtering a ngFor, it's the following:
<span *ngFor="item of itemsList" >
<div *ngIf="yourCondition(item)">
your code
</div>
</span>
Spans are useful because does not inherently represent anything.
You could also use the following:
<template ngFor let-item [ngForOf]="itemsList">
<div *ng-if="conditon(item)"></div>
</template>
This will only show the div if your items matches the condition
See the angular documentation for more information
If you would also need the index, use the following:
<template ngFor let-item [ngForOf]="itemsList" let-i="index">
<div *ng-if="conditon(item, i)"></div>
</template>
pipes in Angular2 are similar to pipes on the command line. The output of each preceding value is fed into the filter after the pipe which makes it easy to chain filters as well like this:
<template *ngFor="#item of itemsList">
<div *ngIf="conditon(item)">{item | filter1 | filter2}</div>
</template>
I know its an old question, however, I thought it might be helpful to offer another solution.
equivalent of AngularJS of this
<div *ng-for="#item of itemsList" *ng-if="conditon(item)"></div>
in Angular 2+ you cant use *ngFor and *ngIf on a same element, so it will be following:
<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.
There is a dynamic filter pipe that I use
Source data:
items = [{foo: 'hello world'}, {foo: 'lorem ipsum'}, {foo: 'foo bar'}];
In the template you can dinamically set the filter in any object attr:
<li *ngFor="let item of items | filter:{foo:'bar'}">
The pipe:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: any[], filter: Record<string, any>): any {
if (!items || !filter) {
return items;
}
const key = Object.keys(filter)[0];
const value = filter[key];
return items.filter((e) => e[key].indexOf(value) !== -1);
}
}
Don't forget to register the pipe in your app.module.ts declarations
Pipe would be best approach. but below one would also work.
<div *ng-for="#item of itemsList">
<ng-container *ng-if="conditon(item)">
// my code
</ng-container>
</div>
For this requirement, I implement and publish a generic component. See
https://www.npmjs.com/package/w-ng5
For use this components, before, install this package with npm:
npm install w-ng5 --save
After, import module in app.module
...
import { PipesModule } from 'w-ng5';
In the next step, add in declare section of app.module:
imports: [
PipesModule,
...
]
Sample use
Filtering simple string
<input type="text" [(ngModel)]="filtroString">
<ul>
<li *ngFor="let s of getStrings() | filter:filtroString">
{{s}}
</li>
</ul>
Filtering complex string - field 'Value' in level 2
<input type="text" [(ngModel)]="search">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering complex string - middle field - 'Value' in level 1
<input type="text" [(ngModel)]="search3">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.valor1', value: search3}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering complex array simple - field 'Nome' level 0
<input type="text" [(ngModel)]="search2">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'nome', value: search2}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering in tree fields - field 'Valor' in level 2 or 'Valor' in level 1 or 'Nome' in level 0
<input type="text" [(ngModel)]="search5">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.valor2', value: search5}, {field:'n1.valor1', value: search5}, {field:'nome', value: search5}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
Filtering nonexistent field - 'Valor' in nonexistent level 3
<input type="text" [(ngModel)]="search4">
<ul>
<li *ngFor="let s of getComplexTypesExtends() | filter:[{field:'n1.n2.n3.valor3', value: search4}]">
{{s.nome}} - {{s.idade}} - {{s.n1.valor1}} - {{s.n1.n2.valor2}}
</li>
</ul>
This component work with infinite attribute level...
I've created a plunker based off of the answers here and elsewhere.
Additionally I had to add an #Input, #ViewChild, and ElementRef of the <input> and create and subscribe() to an observable of it.
Angular2 Search Filter: PLUNKR (UPDATE: plunker no longer works)
Based on the very elegant callback pipe solution proposed above, it is possible to generalize it a bit further by allowing additional filter parameters to be passed along. We then have :
callback.pipe.ts
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'callback',
pure: false
})
export class CallbackPipe implements PipeTransform {
transform(items: any[], callback: (item: any, callbackArgs?: any[]) => boolean, callbackArgs?: any[]): any {
if (!items || !callback) {
return items;
}
return items.filter(item => callback(item, callbackArgs));
}
}
component
filterSomething(something: Something, filterArgs: any[]) {
const firstArg = filterArgs[0];
const secondArg = filterArgs[1];
...
return <some condition based on something, firstArg, secondArg, etc.>;
}
html
<li *ngFor="let s of somethings | callback : filterSomething : [<whatWillBecomeFirstArg>, <whatWillBecomeSecondArg>, ...]">
{{s.aProperty}}
</li>
This is my code:
import {Pipe, PipeTransform, Injectable} from '#angular/core';
#Pipe({
name: 'filter'
})
#Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any[], field : string, value): any[] {
if (!items) return [];
if (!value || value.length === 0) return items;
return items.filter(it =>
it[field] === value);
}
}
Sample:
LIST = [{id:1,name:'abc'},{id:2,name:'cba'}];
FilterValue = 1;
<span *ngFor="let listItem of LIST | filter : 'id' : FilterValue">
{{listItem .name}}
</span>
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:
<a class="list-group-item"
*ngFor="let album of filteredAlbumList">
</a>
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.
I created the following pipe for getting desired items from a list.
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], filter: string): any {
if(!items || !filter) {
return items;
}
// To search values only of "name" variable of your object(item)
//return items.filter(item => item.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1);
// To search in values of every variable of your object(item)
return items.filter(item => JSON.stringify(item).toLowerCase().indexOf(filter.toLowerCase()) !== -1);
}
}
Lowercase conversion is just to match in case insensitive way.
You can use it in your view like this:-
<div>
<input type="text" placeholder="Search reward" [(ngModel)]="searchTerm">
</div>
<div>
<ul>
<li *ngFor="let reward of rewardList | filter:searchTerm">
<div>
<img [src]="reward.imageUrl"/>
<p>{{reward.name}}</p>
</div>
</li>
</ul>
</div>
Ideally you should create angualr 2 pipe for that. But you can do this trick.
<ng-container *ngFor="item in itemsList">
<div*ngIf="conditon(item)">{{item}}</div>
</ng-container>
This is your array
products: any = [
{
"name": "John-Cena",
},
{
"name": "Brock-Lensar",
}
];
This is your ngFor loop
Filter By :
<input type="text" [(ngModel)]='filterText' />
<ul *ngFor='let product of filterProduct'>
<li>{{product.name }}</li>
</ul>
There I'm using filterProduct instant of products, because i want to preserve my original data.
Here model _filterText is used as a input box.When ever there is any change setter function will call.
In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.
filterProduct = this.products;
_filterText : string;
get filterText() : string {
return this._filterText;
}
set filterText(value : string) {
this._filterText = value;
this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;
}
performProduct(value : string ) : any {
value = value.toLocaleLowerCase();
return this.products.filter(( products : any ) =>
products.name.toLocaleLowerCase().indexOf(value) !== -1);
}
You can do this trick:
<ng-container *ngFor="item in items">
<div *ngIf="conditon(item)">{{ item.value }}</div>
</ng-container>
or
<div *ngFor="item in items">
<ng-container *ngIf="conditon(item)">{{ item.value }}</ng-container>
</div>
Here's an example that I created a while back, and blogged about, that includes a working plunk. 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.
In my case, I filtered an unordered list on some text (filterText) the user entered against the "label" property of the objects in my array with this sort of mark-up:
<ul>
<li *ngFor="let item of _items | filter:{label: filterText}">{{ item.label }}</li>
</ul>
https://long2know.com/2016/11/angular2-filter-pipes/
The first step you create Filter using #Pipe in your component.ts file:
your.component.ts
import { Component, Pipe, PipeTransform, Injectable } from '#angular/core';
import { Person} from "yourPath";
#Pipe({
name: 'searchfilter'
})
#Injectable()
export class SearchFilterPipe implements PipeTransform {
transform(items: Person[], value: string): any[] {
if (!items || !value) {
return items;
}
console.log("your search token = "+value);
return items.filter(e => e.firstName.toLowerCase().includes(value.toLocaleLowerCase()));
}
}
#Component({
....
persons;
ngOnInit() {
//inicial persons arrays
}
})
And data structure of Person object:
person.ts
export class Person{
constructor(
public firstName: string,
public lastName: string
) { }
}
In your view in html file:
your.component.html
<input class="form-control" placeholder="Search" id="search" type="text" [(ngModel)]="searchText"/>
<table class="table table-striped table-hover">
<colgroup>
<col span="1" style="width: 50%;">
<col span="1" style="width: 50%;">
</colgroup>
<thead>
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of persons | searchfilter:searchText">
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>
After some googling, I came across ng2-search-filter. In will take your object and apply the search term against all object properties looking for a match.
I was finding somethig for make a filter passing an Object, then i can use it like multi-filter:
i did this Beauty Solution:
filter.pipe.ts
import { PipeTransform, Pipe } from '#angular/core';
#Pipe({
name: 'filterx',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(items: any, filter: any, isAnd: boolean): any {
let filterx=JSON.parse(JSON.stringify(filter));
for (var prop in filterx) {
if (Object.prototype.hasOwnProperty.call(filterx, prop)) {
if(filterx[prop]=='')
{
delete filterx[prop];
}
}
}
if (!items || !filterx) {
return items;
}
return items.filter(function(obj) {
return Object.keys(filterx).every(function(c) {
return obj[c].toLowerCase().indexOf(filterx[c].toLowerCase()) !== -1
});
});
}
}
component.ts
slotFilter:any={start:'',practitionerCodeDisplay:'',practitionerName:''};
componet.html
<tr>
<th class="text-center"> <input type="text" [(ngModel)]="slotFilter.start"></th>
<th class="text-center"><input type="text" [(ngModel)]="slotFilter.practitionerCodeDisplay"></th>
<th class="text-left"><input type="text" [(ngModel)]="slotFilter.practitionerName"></th>
<th></th>
</tr>
<tbody *ngFor="let item of practionerRoleList | filterx: slotFilter">...
Most simple and easy way to limit your ngFor is given below
<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" >{{item.text}}</li>

Categories