Showing posts from December, 2019

NgTrueValue NgFalseValue equivalent directive in angular 2+

Code : import {Directive, ElementRef, forwardRef, HostListener, Input, Renderer2} from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; @Directive({     selector: 'input[type=radio][trueFalseValue]',     providers: [         {             provide: NG_VALUE_ACCESSOR,             useExisting: forwardRef(() => TrueFalseValueDirective),             multi: true         }     ] }) export class TrueFalseValueDirective implements ControlValueAccessor {     @Input() trueValue = true;     @Input() falseValue = false;     constructor(private elementRef: ElementRef, private renderer: Renderer2) {}     private propagateChange = (_: any) => {};     @HostListener('change', ['$event'])     onHostChange(ev) {         this.propagateChange( ? this.trueValue : this.falseValue);     }     writeValue(obj: any): void {         if (obj == null) {             this.propagateChange(

Image lazy load directive code in angular 2+

Code : import {Directive, HostBinding, Input, OnInit} from '@angular/core'; // Define the Directive meta data @Directive({     selector: '[img-preloader]', }) // Class must implement OnInit for @Input() export class ImagePreloaderDirective implements OnInit {     @HostBinding('attr.src') finalImage;     @Input('img-preloader') targetSource: string;     downloadingImage: any; // In class holder of remote image     // finalImage: any; // property bound to our host attribute.     // Set an input so the directive can set a default image.     @Input() defaultImage = 'assets/imgs/img-loader.svg';     @Input() errorImage = 'assets/imgs/img-placeholder.svg';     constructor() {         this.finalImage = this.defaultImage;     }     // ngOnInit is needed to access the @inputs() variables. these aren't available on constructor()     ngOnInit() {         // First set the final image to some default image while we prep

Safe HTML pipe in angular 2+

Code :  import {Pipe, PipeTransform} from '@angular/core'; import {DomSanitizer} from '@angular/platform-browser'; @Pipe({   name: 'safeHtml' }) export class SafeHtmlPipe implements PipeTransform {   constructor(private sanitizer: DomSanitizer) {}   transform(value: any, args?: any): any {     return this.sanitizer.bypassSecurityTrustHtml(value);     // return this.sanitizer.bypassSecurityTrustStyle(style);     // return this.sanitizer.bypassSecurityTrustXxx(style); - see docs   } } How to use: {{ varContainingSomeHTML| safeHtml }}

Make your angular ionic app offline runnable using Ionic Storage

You might be aware that we can make web application offline runnable using service woker. But service worker doesn't work with Ionic hybrid mobile apps as those are blocked webview. Obvious another solution in such case is to use Ionic Storage to cache all required data and then use it as required. After digging deep I realized that I only need to cache the responses of HTTP GET request in my case, as assets and other static stuffs are already served by cordova wether its offline or online mode. So I wrote a custome injectable service which internally uses HttpClient. This implementaion is kind of wrapper for HttpClient class. All I deed is wrote a get() method in a service which is capable of checking network connectivity and based on that make a dicision whether to return cached response or make a actual HTTP GET call using HttpClient, cache the response and then return it back.  Instead of directly using HttpClient, I'm using this new service to make GET calls.

Positive number pipe in angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({   name: 'positive' }) export class PositivePipe implements PipeTransform {   transform(value: number, args?: any): any {     return Math.abs(value);   } } How to use: {{ someNumber| positive }}

Orderby pipe in angular 2+

Code:  import {Pipe, PipeTransform} from '@angular/core'; import * as _ from 'lodash'; import {Many} from 'lodash'; @Pipe({   name: 'orderBy',   pure: false }) export class OrderByPipe implements PipeTransform {   transform(items: any[], args?: string[], orders?: Many<boolean|'asc'|'desc'>): any {     if (args && args.length > 0) {       if (orders) {         return _.orderBy(items, args, orders);       } else {         return _.orderBy(items, args, 'asc');       }     } else {       return items;     }   } } How to use: {{ someList | orderBy: ['createdOn']: 'desc' }}

Hightlight text in search result using pipe angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({   name: 'highlightSearch' }) export class HighlightSearchPipe implements PipeTransform {   transform(value: any, args: any): any {     if (!args) {return value; }     const re = new RegExp(args, 'gi'); // 'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.     return value.replace(new RegExp(args, 'gi'), '<span font-bold>$&</span>'/*re, '<span font-bold>' + args + '</span>'*/);   } } How to use: {{someStringVar | highlightSearch: textToHighlight | safeHtml}}

Groupby pipe in angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({   name: 'groupby' }) export class GroupbyPipe implements PipeTransform {   transform(collection: Array<any>, property: string): Array<any> {     // prevents the application from breaking if the array of objects doesn't exist yet     if (!collection) {       return null;     }     const groupedCollection = collection.reduce((previous, current) => {       if (!previous[current[property]]) {         previous[current[property]] = [current];       } else {         previous[current[property]].push(current);       }       return previous;     }, {});     // this will return an array of objects, each object containing a group of objects     return Object.keys(groupedCollection).map(key => ({ key, value: groupedCollection[key] }));   } }

Filter pipe angular 2+

Code: import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'filter',  pure: false }) 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);   } } How to use:  someList | filter: 'enabled': true"