I\'m looking for the angular 2 way to do this.
I simply have a list of items, and I want to make an input whos job is to filter the list.
Search by multiple fields
Assuming Data:
items = [
{
id: 1,
text: 'First item'
},
{
id: 2,
text: 'Second item'
},
{
id: 3,
text: 'Third item'
}
];
Markup:
<input [(ngModel)]="query">
<div *ngFor="let item of items | search:'id,text':query">{{item.text}}</div>
Pipe:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'search'
})
export class SearchPipe implements PipeTransform {
public transform(value, keys: string, term: string) {
if (!term) return value;
return (value || []).filter(item => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
}
}
One line for everything!
<md-input placeholder="Item name..." [(ngModel)]="name" (keyup)="filterResults()"></md-input>
<div *ngFor="let item of filteredValue">
{{item.name}}
</div>
filterResults() {
if (!this.name) {
this.filteredValue = [...this.items];
} else {
this.filteredValue = [];
this.filteredValue = this.items.filter((item) => {
return item.name.toUpperCase().indexOf(this.name.toUpperCase()) > -1;
});
}
}
Don't do any modification on 'items' array(list of items from which results are filtered). When searched item 'name' is empty return the complete list of 'items', if not compare the 'name' with every 'name' in the 'items ' array and filter out only the name that is present in 'items' array and store it in the 'filteredValue'.
Pipes in Angular 2+ are a great way to transform and format data right from your templates.
Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.
List of Built-in Pipes from API List Examples
{{ user.name | uppercase }}
Example of Angular version 4.4.7. ng version
Custom Pipes which accepts multiple arguments.
HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS « transform(json: any[], args: any[]) : any[] { ... }
Filtering the content using a Pipe « json-filter-by.pipe.ts
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]) : any[] {
var searchText = args[0];
var jsonKey = args[1];
// json = undefined, args = (2) [undefined, "name"]
if(searchText == null || searchText == 'undefined') return json;
if(jsonKey == null || jsonKey == 'undefined') return json;
// Copy all objects of original array into new Array.
var returnObjects = json;
json.forEach( function ( filterObjectEntery ) {
if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
console.log('Search key is available in JSON object.');
if ( typeof filterObjectEntery[jsonKey] != "undefined" &&
filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
} else {
// object didn't match a filter value so remove it from array via filter
returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
}
} else {
console.log('Search key is not available in JSON object.');
}
})
return returnObjects;
}
}
Add to @NgModule
« Add JsonFilterByPipe
to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy
. If you add to module then it is available to all the component's of that module.
@NgModule({
imports: [
CommonModule,
RouterModule,
FormsModule, ReactiveFormsModule,
],
providers: [ StudentDetailsService ],
declarations: [
UsersComponent, UserComponent,
JsonFilterByPipe,
],
exports : [UsersComponent, UserComponent]
})
export class UsersModule {
// ...
}
File Name: users.component.ts
and StudentDetailsService
is created from this link.
import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: [ './users.component.css' ],
providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy {
students: MyStudents[];
selectedStudent: MyStudents;
constructor(private studentService: StudentDetailsService) { }
ngOnInit(): void {
this.loadAllUsers();
}
ngOnDestroy(): void {
// ONDestroy to prevent memory leaks
}
loadAllUsers(): void {
this.studentService.getStudentsList().then(students => this.students = students);
}
onSelect(student: MyStudents): void {
this.selectedStudent = student;
}
}
File Name: users.component.html
<div>
<br />
<div class="form-group">
<div class="col-md-6" >
Filter by Name:
<input type="text" [(ngModel)]="searchText"
class="form-control" placeholder="Search By Category" />
</div>
</div>
<h2>Present are Students</h2>
<ul class="students">
<li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
<a *ngIf="student" routerLink="/users/update/{{student.id}}">
<span class="badge">{{student.id}}</span> {{student.name | uppercase}}
</a>
</li>
</ul>
</div>
This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {
transform(json: any[], args: any[]): any[] {
const searchText = args[0];
const jsonKey = args[1];
let jsonKeyArray = [];
if (searchText == null || searchText === 'undefined') { return json; }
if (jsonKey.indexOf(',') > 0) {
jsonKey.split(',').forEach( function(key) {
jsonKeyArray.push(key.trim());
});
} else {
jsonKeyArray.push(jsonKey.trim());
}
if (jsonKeyArray.length === 0) { return json; }
// Start with new Array and push found objects onto it.
let returnObjects = [];
json.forEach( function ( filterObjectEntry ) {
jsonKeyArray.forEach( function (jsonKeyValue) {
if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
// object value contains the user provided text.
returnObjects.push(filterObjectEntry);
}
});
});
return returnObjects;
}
}
Now, instead of
jsonFilterBy:[ searchText, 'name']
you can do
jsonFilterBy:[ searchText, 'name, other, other2...']
In angular 2 we don't have pre-defined filter and order by as it was with AngularJs, we need to create it for our requirements. It is time killing but we need to do it, (see No FilterPipe or OrderByPipe). In this article we are going to see how we can create filter called pipe in angular 2 and sorting feature called Order By. Let's use a simple dummy json data array for it. Here is the json we will use for our example
First we will see how to use the pipe (filter) by using the search feature:
Create a component with name category.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-category',
templateUrl: './category.component.html'
})
export class CategoryComponent implements OnInit {
records: Array<any>;
isDesc: boolean = false;
column: string = 'CategoryName';
constructor() { }
ngOnInit() {
this.records= [
{ CategoryID: 1, CategoryName: "Beverages", Description: "Coffees, teas" },
{ CategoryID: 2, CategoryName: "Condiments", Description: "Sweet and savory sauces" },
{ CategoryID: 3, CategoryName: "Confections", Description: "Desserts and candies" },
{ CategoryID: 4, CategoryName: "Cheeses", Description: "Smetana, Quark and Cheddar Cheese" },
{ CategoryID: 5, CategoryName: "Grains/Cereals", Description: "Breads, crackers, pasta, and cereal" },
{ CategoryID: 6, CategoryName: "Beverages", Description: "Beers, and ales" },
{ CategoryID: 7, CategoryName: "Condiments", Description: "Selishes, spreads, and seasonings" },
{ CategoryID: 8, CategoryName: "Confections", Description: "Sweet breads" },
{ CategoryID: 9, CategoryName: "Cheeses", Description: "Cheese Burger" },
{ CategoryID: 10, CategoryName: "Grains/Cereals", Description: "Breads, crackers, pasta, and cereal" }
];
// this.sort(this.column);
}
}
<div class="col-md-12">
<table class="table table-responsive table-hover">
<tr>
<th >Category ID</th>
<th>Category</th>
<th>Description</th>
</tr>
<tr *ngFor="let item of records">
<td>{{item.CategoryID}}</td>
<td>{{item.CategoryName}}</td>
<td>{{item.Description}}</td>
</tr>
</table>
</div>
2.Nothing special in this code just initialize our records variable with a list of categories, two other variables isDesc and column are declared which we will use for sorting latter. At the end added this.sort(this.column); latter we will use, once we will have this method.
Note templateUrl: './category.component.html', which we will create next to show the records in tabluar format.
For this create a HTML page called category.component.html, whith following code:
3.Here we use ngFor to repeat the records and show row by row, try to run it and we can see all records in a table.
Search - Filter Records
Say we want to search the table by category name, for this let's add one text box to type and search
<div class="form-group">
<div class="col-md-6" >
<input type="text" [(ngModel)]="searchText"
class="form-control" placeholder="Search By Category" />
</div>
</div>
5.Now we need to create a pipe to search the result by category because filter is not available as it was in angularjs any more.
Create a file category.pipe.ts and add following code in it.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'category' })
export class CategoryPipe implements PipeTransform {
transform(categories: any, searchText: any): any {
if(searchText == null) return categories;
return categories.filter(function(category){
return category.CategoryName.toLowerCase().indexOf(searchText.toLowerCase()) > -1;
})
}
}
6.Here in transform method we are accepting the list of categories and search text to search/filter record on the list. Import this file into our category.component.ts file, we want to use it here, as follows:
import { CategoryPipe } from './category.pipe';
@Component({
selector: 'app-category',
templateUrl: './category.component.html',
pipes: [CategoryPipe] // This Line
})
7.Our ngFor loop now need to have our Pipe to filter the records so change it to this.You can see the output in image below
enter image description here
You can also create a search pipe to filter results:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name : 'searchPipe',
})
export class SearchPipe implements PipeTransform {
public transform(value, key: string, term: string) {
return value.filter((item) => {
if (item.hasOwnProperty(key)) {
if (term) {
let regExp = new RegExp('\\b' + term, 'gi');
return regExp.test(item[key]);
} else {
return true;
}
} else {
return false;
}
});
}
}
Use pipe in HTML :
<md-input placeholder="Item name..." [(ngModel)]="search" ></md-input>
<div *ngFor="let item of items | searchPipe:'name':search ">
{{item.name}}
</div>