Creating a custom pipe | split() | Angular
Kenan
Posted on August 25, 2020
Pipes are a great way to manipulate data in a template. Out of the box, we get pipes for a date, currency and etc.
But there is always a situation occurs where you need to create your own custom pipes.
In my case, I needed to split tracking_number
which was in a format like: 10001-TY778899
(user id-package id)
Now, I could serialize package_id alone in the backend, but, let's face it. I was too lazy for that. So I had to do it in the frontend.
Let's come to the actual part.
Step 1: Create a pipe template and name it split
ng g pipe pipes/split
We will have this template:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'split'
})
export class SplitPipe implements PipeTransform {
transform(value: unknown, ...args: unknown[]): unknown {
return null;
}
}
Change parameters and write the code that splits string.
Example use case
we have text
argument which is the text in a template
{{ this is where we'll split | split: " " }}
I tried to split by space
in the above example.
The Code
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'split'
})
export class SplitPipe implements PipeTransform {
transform(text: string, by: string, index: number = 1) {
let arr = text.split(by); // split text by "by" parameter
return arr[index] // after splitting to array return wanted index
}
}
Now, about that tracking_number
, I needed the right part of 10001-TY778899 after splitting by - (hyphen) so in my case, I set default index number 1 hoping that I will get TY778899 which I actually did!
Use Case
Before:
<tr *ngFor="let p of user.stored_packages" (click)="package = p">
<td>{{ p.id }}</td>
<td>{{ p.tracking_number | split: "-" }}</td>
<td>{{ p.courier_id }}</td>
</tr>
If you ever need particular index, keep in mind that you can use it like this
<td>{{ p.tracking_number | split: "-": 0 }}</td>
Well, this was a simple custom pipe example in Angular
If you are interested in Django, Vue.js too, I invite you to check out these projects that I made with love ❤
Kenan7 / corvento_backend
Check out the frontend part that I wrote in Vue.js https://github.com/Kenan7/corvento_frontend
Kenan7 / corvento_frontend
All online events in one place during the pandemic
corvento-frontend
Project setup
npm install
Compiles and hot-reloads for development
npm run serve
Compiles and minifies for production
npm run build
Lints and fixes files
npm run lint
Customize configuration
Posted on August 25, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.