Angular Slugify Pipe For Your Angular Url Seo Friendly Applications.
Web applications more than often rely on good SEO. One part of the SEO puzzle is creating SEO-friendly URLS.
A good SEO friendly url should describe your content, include keywords, use hyphens to separate words, use lowercase letters and if possible keep it short.
To solve this in Angular web applications, an Angular Pipe should be an awesome place to start.
So what's a pipe, lets take as an example where you store data to your back-end. One of the fields holds a date of string: Thursday April 2019 00:28:12 ....
Now you want to display this date to your clients, I bet such an ugly date string is not anyone wants to see on a web page.
To solve such an issue, where developers are able to transform data in the front-end without touching the data in the back-end, Angular pipes come in.
In our date case above, Angular already has some build in Pipes, and the DatePipe is among them.
In our case, Angular doesn't come with a URL slugify pipe yet. So we have to write one for ourselves.
Angular is one big framework that can be intimidating for a start. But once you grab some simple understanding, it becomes enjoyable playing around with the different features.
Pipes are just JavaScript functions. For a SlugifyPipe, we want to return a string that is lowercase, stripped of unwanted characters, spaces replaced with hyphens..
Below is our SlugifyPipe. It takes in an anguement of a string, transforms it to lowercase, trims it and replaces any special characters with space which are then replaced with hyphens.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
How easy was that? We didn't have to install a whole library to achieve such simple functionality.
To use it in our component class:
Simply provide the Slugify pipe as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
To use our pipe in the component template, we just need to pipe in the string as shown below:
1 2 |
|