-
-
Notifications
You must be signed in to change notification settings - Fork 0
Format With Pipes in Angular
Tyler Ruff edited this page Jul 1, 2022
·
1 revision
Formatting date objects in Angular is relatively simple, using the DayJS library.
- Install dayjs
npm install dayjs
- 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');
}
}
- Insert the pipe into the declarations (in app.module.ts)
@NgModule({
declarations: [
...
FormatDatePipe,
...
]
})
- Use in component.html like so:
...
<time class="text-sm text-gray-600">
{{ post.publishedAt | formatDate }}
</time>
...
- 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;
}
}
- Insert the pipe into the declarations (in app.module.ts)
@NgModule({
declarations: [
...
StringLengthPipe,
...
]
})
- 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>
...
- 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;
}
}
- Insert the pipe into the declarations (in app.module.ts)
@NgModule({
declarations: [
...
GetMbPipe,
...
]
})
- Use in component.html like so:
...
<span>
{{ fileSize | getMb }}
</span>
...
Join the Blazed Development Group today to get involved in open source collaborative projects.
Discover our FREE learning resources, the Blazed University, Web Development School, and Blazed City.