How to Shorten URL using Custom Pipe in Angular

Introduction

In this tutorial, I will show steps to create a custom pipe that shortens a long URL or Link. The Pipes are the best way to transform the appearance of elements in the template. There are built-in pipes like Date pipes, Currency pipes, and Number pipes, etc in Angular. But if these pipes can't fulfill the requirements, then we can build our own pipe in Angular is called Custom Pipe in Angular.

Note: Before going through this session, please visit my previous article related to Angular applications as mentioned below.

Angular Application

Step 1. Create JSON Data File

A JSON file is a useful file that helps to store simple data structures and objects in JSON format, typically known as JavaScript Object Notation.  It used for transferring data between a web application and a server. Add json in path src/app/users.json.

It contains the property names are id, name, username, email and source.

[{
    "id": 1,
    "name": "satya1",
    "username": "Bret",
    "email": "[email protected]",
    "source": "https://www.satya1.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 2,
    "name": "satya2",
    "username": "Antonette",
    "email": "[email protected]",
    "source": "https://www.satya2.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 3,
    "name": "satya3",
    "username": "Samantha",
    "email": "[email protected]",
    "source": "https://www.satya3.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 4,
    "name": "satya4",
    "username": "Karianne",
    "email": "[email protected]",
    "source": "https://www.satya4.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 5,
    "name": "satya5",
    "username": "Kamren",
    "email": "[email protected]",
    "source": "https://www.satya5.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 6,
    "name": "satya6",
    "username": "Leopoldo_Corkery",
    "email": "[email protected]",
    "source": "https://www.satya6.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 7,
    "name": "satya7",
    "username": "Elwyn.Skiles",
    "email": "[email protected]",
    "source": "https://www.satya7.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 8,
    "name": "satya8",
    "username": "Maxime_Nienow",
    "email": "[email protected]",
    "source": "https://www.satya8.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 9,
    "name": "satya9",
    "username": "Delphine",
    "email": "[email protected]",
    "source": "https://www.satya9.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  },
  {
    "id": 10,
    "name": "satya10",
    "username": "Moriah.Stanton",
    "email": "[email protected]",
    "source": "https://www.c-sharpcorner.com/article/build-temparature-convertor-application-using-angular-and-bootstrap/"
  }
]

Step 2. Create User Interface

Now get into the app.component.ts file, import the UsersJson file and create the USERS interface. The USERS interface contains these fields which are same JSON property names (id, name, username, email, source).

import { Component } from '@angular/core';
import UsersJson from './users.json';
  
interface USERS {
    id: Number;
    name: String;
    username: String;
    email: String;
    source: string;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  
  Users: USERS[] = UsersJson;
  constructor(){
    console.log(this.Users);
  }
}

Step 3. Create Bootstrap Table

We can show each user details using *ngFor directive. *ngFor is a built-in template directive that makes it easy to iterate over something like an array or an object and create a template for each item. 

<div class="container mt-5">
  
  <h2>Angular Custom Pipe</h2>
  
  <table class="table table-striped">
    <thead>
        <tr>
          <th>Id</th>
          <th>Name</th>
          <th>Employee Name</th>
          <th>Employee Email</th>
          <th>Employee Url</th>
        </tr>
    </thead>
    <tbody>
      <tr *ngFor="let user of Users">
        <td>{{ user.id }}</td>
        <td>{{ user.name }}</td>
        <td>{{ user.username }}</td>
        <td>{{ user.email }}</td>
        <td><p><a [href]="user.source">{{user.source}}</a></td>
      </tr>
    </tbody>
  </table>
</div>

Step 4. Update tsconfig JSON

Before you start the application, you have to tweak your tsconfig.json file, define the resolveJsonModule and esModuleInterop inside the compilerOptions object.

{
  "compileOnSave": false,
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "baseUrl": "./",

Step 5. Run Angular App

Now, you can open the terminal and start writing the given command and hit enter to start the angular app.

ng serve --open

Output

Here we learn steps to fetch data from JSON file and display data in a table. We also looked at steps to use the *ngFor directive to showcase json data. 

The output shows user information with URL which are very long URL and it's difficult to adjust in table.

URL shortener in angular

Step 6. Create a pipe that shortens a long URL or Link

Use the command in a terminal window ng g p pipes/ShortUrl to use the Angular CLI to generate Custom Url Shortener Pipe inside the pipes folder.

URL shortener in angular

Step 7. Open the short-url.pipe.ts file and add code

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'shortUrl'
})
export class ShortUrlPipe implements PipeTransform {

  transform(url: string, args?: any): any {
    if (url) {
      const len = url.length;
      if (len > 30) // only shorten if greater than 30
        // change value 21 and 9 as per requirement
        return url.substr(0, 21) + '...' + url.substring(len - 9, len);
      return url;
    }
    return url;
  }
}

Step 8. Import Custom Domain Pipe in app.modules.ts

Import our Custom Domain Pipe in app.modules.ts file and add it to the declarations: [] array.

Note: Do this if you did not use the Angular CLI to generate the ShortUrlPipe, otherwise the import should already be there as Angular CLI does it for you.

import { ShortUrlPipe } from './pipes/short-url.pipe';
 
@NgModule({
  declarations: [
    ShortUrlPipe
  ],

Step 9. Update the app.component.html file

<tbody>
    <tr *ngFor="let user of Users">
      <td>{{ user.id }}</td>
      <td>{{ user.name }}</td>
      <td>{{ user.username }}</td>
      <td>{{ user.email }}</td>
      <!-- <td><p><a [href]="user.source">{{user.source}}</a></td> -->
      <td><p><a [href]="user.source">{{user.source|shortUrl}}</a></td>
    </tr>
</tbody>

The custom pipe called shortUrl is implemented in source column.

<td><p><a [href]="user.source">{{user.source|shortUrl}}</a></td>

Step 10. Add the Bootstrap CSS path in angular.json file

It is used to enable the styling after install the latest version of Bootstrap in angular. 

npm install bootstrap --save

Add the Bootstrap CSS path in angular.json

 "styles": [
              "src/styles.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],

Output

Now you can see result under Employee Url section that custom pipe shortens a long URL or Link.

URL shortener in angular

Summary

In this write-up, we have learned the details below.

  • Steps to fetch data from JSON file and display data in an Angular table
  • Create a custom URL or Link shortener Pipe in Angular

Thank You & Stay Tuned For More