Skip to content

Format With Pipes in Angular

Tyler Ruff edited this page Jul 1, 2022 · 1 revision

Date Pipe

Formatting date objects in Angular is relatively simple, using the DayJS library.

  1. Install dayjs
npm install dayjs
  1. Create format-date pipe (format-date.pipe.ts)
import { Pipe, PipeTransform } from '@angular/core';
import * as dayjs from 'dayjs';

@Pipe({ name: 'formatDate' })
export class FormatDatePipe implements PipeTransform {
 constructor() {}

 transform(value: any): string {
  return dayjs(value).format('DD/MM/YYYY');
 }
}
  1. Insert the pipe into the declarations (in app.module.ts)
@NgModule({
 declarations: [
  ...
  FormatDatePipe,
  ...
 ]
})
  1. Use in component.html like so:
 ...
 <time class="text-sm text-gray-600">
  {{ post.publishedAt | formatDate }}
 </time>
 ...

Sources

Snip String if Greater than a Certain Length Pipe

  1. Create stringlength pipe (stringlength.pipe.ts)
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'stringLength' })
export class StringLengthPipe implements PipeTransform {
 constructor() {}

 transform(value: any, maxLength?: number): string {
  if (!maxLength) { maxLength = 20; }
  if(value.length > maxLength){
    return value.slice(0, maxLength) + "...";
  }
  return value; 
 }
}
  1. Insert the pipe into the declarations (in app.module.ts)
@NgModule({
 declarations: [
  ...
  StringLengthPipe,
  ...
 ]
})
  1. Use in component.html like so:
  • Default (20 characters or less)
 ...
 <span>
  {{ user.name | stringLength }}
 </span>
 ...
  • Custom character length (12 characters or less)
 ...
 <span>
  {{ user.name | stringLength: 12 }} 
 </span>
 ...

Sources

Bytes to KB/MB/GB/TB Pipe

  1. Create getmb pipe (getmb.pipe.ts)
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'getMb' })
export class GetMbPipe implements PipeTransform {
 constructor() {}

 transform(value: any): string {
  var result: string = "";
  //convert to number
  var bytes: number = +value;
  //raise to the negative 6th power
  var kb: number = bytes / 1000;
  var mb: number = 0;
  var gb: number = 0;
  var tb: number = 0;
  result = `${kb} KB`;
  //check whether or not to also get MB/GB/TB value
  if(kb >= 1000){
    mb = kb / 1000;
    result = `${mb} MB`;
    if(mb >= 1000){
        gb = mb / 1000;
        result = `${gb} GB`;
        if(gb >= 1000){
            tb = gb / 1000;
            result = `${tb} TB`;
        }
      }
  }

  return result; 
 }
}
  1. Insert the pipe into the declarations (in app.module.ts)
@NgModule({
 declarations: [
  ...
  GetMbPipe,
  ...
 ]
})
  1. Use in component.html like so:
 ...
 <span>
  {{ fileSize | getMb }}
 </span>
 ...

Sources