UNPKG

@ioniczoo/bird-format-pipe

Version:

Format Pipe for Ionic

77 lines (68 loc) 1.8 kB
import { NgModule, Pipe, PipeTransform } from '@angular/core'; /** * Generated class for the FormatPipe pipe. * * See https://angular.io/api/core/Pipe for more info on Angular Pipes. * * @example * ``` html * {{ cpf | format:'999.999.999-99' }} * {{ tel | format:'(99) 9 9999-9999' }} * ``` */ @Pipe({ name: 'format' }) export class FormatPipe implements PipeTransform { /** * Format value. * * @param {any} value Waits to receive string or integer * @param {string} pattern Waits to receive a pattern in string * @return {[type]} returns a formatted string. */ transform(value: any, pattern: string) { return this.format(String(value), pattern); } /** * Format value * @param {string} value virgin value. * @param {string} pattern standard format. * @return {string} returns a formatted string. */ private format(value: string, pattern: string): string { let data: string = '', cont: number = 0, plus: string = ''; for (let i = 0; i < pattern.length; i++) { if (parseInt(pattern[i])) { cont++ } } /** * Addes zeros to the left to complete the characters in the format. */ if (cont > value.length) { for (let i = 0; i < cont - value.length; i++) { plus = plus.concat('0') } value = plus + value } cont = 0 /** * Replaces pattern numbers with values. */ for (let i = 0; i < pattern.length; i++) { if (parseInt(pattern[i]) && cont < value.length) { data = data.concat(value[cont]) cont++ } else { data = data.concat(pattern[i]) } } return data } } @NgModule({ declarations: [FormatPipe], exports: [FormatPipe] }) export class FormatPipeModule {}