Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Angular Pipes

  • Object Filter - objectfilter.pipe.ts
  • Object Sum - objectsum.pipe.ts
  • Money Formatter - money.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'money'
})
export class MoneyPipe implements PipeTransform {
transform(value: number, symbol?: string): string {
if(typeof value == 'undefined') return null;
let matches = String(value.toFixed(2)).match(/(-*)(\d*)\.?(\d*)/);
let integers = this.reverse(this.split(this.reverse(matches[2])).join('.'));
let decimals = matches[3];
let formatted = matches[1] + integers + ',' + decimals;
return symbol ? formatted + ' ' + symbol : formatted;
}
private reverse(str:string):string{
return str.split('').reverse().join('');
}
private split(str:string):Array<string>{
let rtn = [];
for(let i = 0; i < str.length; i = i + 3)
rtn.push(str.substring(i, i + 3));
return rtn;
}
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'objectfilter'
})
export class ObjectfilterPipe implements PipeTransform {
transform(items:any[], search:string, keys?:Array<string>):any {
return typeof items == 'undefined' || search == '' || typeof search == 'undefined' ? items : items.filter(item => this.match(item, search, keys));
}
private match(item:any[], search:string, keys?:Array<string>):Boolean{
let flat = this.flatten(item, keys);
for(let query of search.split(' '))
if(!flat.match(new RegExp(query, 'i')))
return false;
return true;
}
private flatten(items:any[], keys?:Array<string>, route?:string):string{
let val:string = '';
for(let key of Object.keys(items)){
let currentRoute = typeof route == 'undefined' ? key : route + '.' + key;
if(typeof items[key] == 'object')
val = val + this.flatten(items[key], keys, currentRoute);
else if(items[key] !== '' && typeof items[key] !== 'undefined' && (typeof keys == 'undefined' || keys.indexOf(currentRoute) >= 0))
val = val + items[key];
}
return val;
}
}
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'objectsum'
})
export class ObjectsumPipe implements PipeTransform {
transform(items:any[], path:string):number {
let sum: number = 0;
for(let item of items){
let keys = path.split('.');
while(keys.length && (item = item[keys.shift()]));
sum += +item;
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.