cf-common-lib
v2.0.5
Published
Object Validators and Utilities
Downloads
25
Maintainers
Readme
Angular CF common Library
Download stats
Validators and Utilities This library exposes some services to processs object list; common pipes, directives, validates some standard Indian unique identifiers and helps to detect device being used currently.
Instllation
npm install cf-common-lib --save-dev
How to use this module?
Include CfCommonModule
inside import meta section of NgModule
decorator
import { NgModule } from '@angular/core';
import { CfCommonModule } from 'cf-common-lib'
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
CfCommonModule // <-Include this one
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Valitdators for PAN, AADHAAR/VID (virtual ID) , Pincode, GSTIN (Indian)
Import and Include ValidatorService
service in component.ts
flie
import { ValidatorService} from 'cf-common-lib' ;
@Component({
//.....
})
export class AppComponent {
constructor(private validate: ValidatorService){
console.log(this.validate.aadhaarCheck('999999999999')) // true
console.log(this.validate.aadhaarCheck('9999 9999 9999')) // true
console.log(this.validate.aadhaarCheck('9999 9999 9999 0000')) // true VID check
console.log(this.validate.panCheck('bhjka5871m')) // true
console.log(this.validate.gstinCheck('29ABCDE1234F2Z5')) // true
console.log(this.validate.pincodeCheck('560094')) // true
}
Device detector
Import and Include DeviceDetectorService
service in component.ts
flie
import { DeviceDetectorService } from 'cf-common-lib' ;
@Component({
//.......
})
export class AppComponent {
constructor( private device : DeviceDetectorService ){
console.log(device.info());
/*It prints
{
"userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/69.0.3497.81 Chrome/69.0.3497.81 Safari/537.36",
"browser": "Chrome",
"device": "",
"os_version": "Linux x86_64",
"browser_version": "Chrome 69",
"isDesktop": true,
"isMobile": false,
"isTablet": false
}
*/
}
Utility service
Import and Include UtilityService
service in component.ts
file.
Now lets see how we can query for objects list.
import { Component } from '@angular/core';
import { UtilityService} from 'cf-common-lib' ;
@Component({
//.....
})
export class AppComponent {
books = [{name : 'Nyay' , type : 'book' , author : 'Jaimini'},
{name : 'satyarth' , type : 'book' , author : 'Dayanand'},
{name : 'Sankhya' , type : 'book' , author : 'Kanaad'},
{name : 'Triology of vedas' , type : 'book' , author : 'Gurudatt'},
{name : 'Yog' , type : 'book' , author : 'Patanjali'}]
_sampleArray = [1,2,3,[4,5,6,7,[8,9,10],11],12]
constructor( private utility : UtilityService){
console.log(this.utility.extractKeysFromObjectsList(this.books,'name'));
/* It extracts keys from Array of objects with keyname 'name'
["Nyay", "satyarth", "Sankhya", "Triology of vedas", "Yog"]
*/
//==================================
console.log(this.utility.findInObjectsArrayFromKey(this.books, 'name', 'yog', true)); // true for ignoreCase
/* It finds object from list having key 'name' and value 'yog'
{name: "Yog", type: "book", author: "Patanjali"}
*/
//==================================
console.log( this.utility.objectArrayIndexOf(this.books, 'name', 'Sankhya'));
/* It prints index in array of object list having key value 'Sankhya'
3
*/
//==================================
console.log( this.utility.objectArrayFindFromKey(this.books, 'name', 'Yog'));
/*
{name: "Yog", type: "book", author: "Patanjali"}
*/
//==================================
console.log( this.utility.filterInObjectsArrayFromKey(this.books, 'name', 'Sankhya'));
/* Filters all objects having key 'name' and value 'Sankhya'
[{name: "Sankhya", type: "book", author: "Kanaad"}]
*/
//==================================
console.log( this.utility.filterObjectsFromKeys(this.books,['Patanjali','Jaimini' ], 'author'));
/*Filters all objects from list which matches author as key and list of values ['Patanjali','Jaimini' ]
[{name: "Nyay", type: "book", author: "Jaimini"},
{name: "Yog", type: "book", author: "Patanjali"}]
*/
console.log(this.utility.flattenArray(this._sampleArray));
/* It flattens nested array
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
*/
}
We can do much more complex queries out of above utilities.
Utility service : file injector
This service injects css
or js
files into index.html
file dynamically
Callback function gets exceuted on completion of injecting process
import { UtilityService} from 'cf-common-lib' ;
@Component({
//......
})
export class AppComponent implements OnInit{
filesToInclude = ['./assets/css/file1.css' , './assets/css/file2.css',
'./assets/js/file1.js', './assets/js/file2.js'];
constructor( private utility : UtilityService){}
public _callback(urls) {
console.log("All URLs are now loaded");
}
private loadFiles(){
this.utility.jsCssScriptInjector(this._callback, this.filesToInclude);
}
ngOnInit(){
this.loadFiles();
}
}
Utility service : Objects equality
Checks whether two objects are equal or not (Deep compare).
//............
export class AppComponent implements OnInit{
obj1 = {a :1 , b :2 , e: {c : 4 , d : 5}};
obj2 = {e: {d : 5 , c : 4}, b :2 , a :1};
constructor(private utility : UtilityService){}
console.log(this.utility.isObjectsEqual(this.obj1, this.obj2)); // Returns true;
}
Usefull common directives. NgxDirectiveModule
*ngInit
This is an alternative option of ng-init in build directives of angularJs which intializes variable on load of DOM.
import { NgxDirectiveModule } from 'cf-common'
@NgModule({
imports: [
BrowserModule, NgxDirectiveModule] // <--Include this one
})
export class AppModule { }
use *ngInit
in html as below
<div *ngInit="5+10; let add"> <span>{{add}}</span> </div> <!-- Add will be inittialized with 15, expression can be function call as well -->
click-stop-propagation
Directive to stop default event propogation. In absence of this directive, Event bubbling happens on click with inner click handler.
<div (click)="clickHandler_1()"> click 1
<div (click)="clickHandler_2()" click-stop-propagation>click 2</div>
</div>
Usefull common pipes. NgxPipeModule
lowercase
pipe name from classLowerCasePipe
which converts text to lowercase.
import { NgxPipeModule } from 'cf-common'
@NgModule({
imports: [
BrowserModule, NgxPipeModule] // <--Include this one
})
export class AppModule { }
use lowercase
in html as bellow
<div>{{'CaPiTalFloat' | lowercase}}</div>
<!--prints 'capitalfloat' -->
uppercase
pipe name from classUpperCasePipe
which transforms text to titilecase. useuppercase
in html as bellow
<div>{{'CaPiTalFloat' | uppercase}}</div>
<!--prints 'CAPITALFLOAT' -->
titlecase
pipe name from classTitleCasePipe
which transforms text to titilecase. usetitlecase
in html as bellow
<div>{{'CaPiTalFloat' | titlecase}}</div>
<!--prints 'Capitalfloat' -->
keys
pipe name from classKeysPipe
which transforms object to key value.
use keys
in html as bellow
items = {name : "satya", value : 3000 }
<div *ngFor="let item of items | keys ; index as i ;">
K : {{item.key}}, V : {{item.value}}
<!--K : name, V : satya
K : value, V : 3000 -->
</div>
generateUrl
pipe name from classGenerateUrlPipe
which replaces{%s%}
to specified value in array
import { GenerateUrlPipe } from 'cf-common' ;
//........
let _url = 'https://www.capitalfloat/api/{%s%}/{%s%}/';
constructor( private generateUrl : GenerateUrlPipe){
console.log(this.generateUrl.transform(_url, ['abcd-efgh-ijkl-mnop-1221', 'profile'] ))
//prints : https://www.capitalfloat/api/abcd-efgh-ijkl-mnop-1221/profile/
}
trim
pipe name from classTrimPipe
which trims value to specified number of charecters as params.
use trim
in html as bellow
<div>{{ 'CaPiTalFloat' | trim :10}}</div>
<!-- CaPiTalF.. -->
timeago
pipe name from classTimeagoPipe
which transforms values to human readable time format.
use timeago
in html as bellow
<div>Updated on : {{ 1540791632000 | timeago }}</div>
<!-- prints: "4 days ago" -->
searchtext
pipe name from classSearchtextPipe
appSourceFilter = [{id:1 , label : 'source1' , name : 'name1'}, {id:2 , label : 'source2' , name : 'name2'}, {id:3 , label : 'source3' , name : 'name3'}]
<input type="text" [(ngModel)]="sourceText" class="formControl"/>
<div *ngFor="let item of appSourceFilter | searchtext :'id,label,name': sourceText">
{{item.label}}
</div>
Above search filter searchtext
displays/filters items according to given input values ....it searches on object's keys id , label and name i.e sourceText can be either id , label or name of appSource
indianCurrency
pipe name from classIndianCurrencyPipe
which transforms values to human readable time format.
use indianCurrency
in html as bellow
<div>{{ 154079 | indianCurrency }}</div> <!-- Prints ₹1,54,079 -->
<div> {{ 154079.29 | indianCurrency }}</div> <!--Prints ₹1,54,079.29 -->
For any suggestions- Write to : [email protected]