Friday, 21 February 2020

Truncate file name without hiding the extension using Angular Pipe

AngularPipeTruncate

In this article we are going to discuss about truncating the file name with out hiding its extension. We can truncate file name only using CSS, but in this case, it will truncate extension as well. Check css example first for "angular-training.pdf"

Css


.truncateClass {
    display: inline-block;
    width: 30px; // your width
    white-space: nowrap;
    overflow: hidden !important;
    text-overflow: ellipsis;
}

Example result: angular...

In the above example it is truncating all the file name including the extension. It is not user friendly; user should know the file extension without hovering or clicking on the file. We can achieve this by using a simple angular pipe.

Example results


angular-[...].pdf

Truncate pipe


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

@Pipe({
  name: 'truncate'
})

export class TruncateName implements PipeTransform{
  transform(name: string): string {
    const ext: string =
      name.substring(name.lastIndexOf('.') + 1, name.length).toLowerCase();
    let newName: string = name.replace('.' + ext, '');
    if (name.length <= 8) {
      // if file name length is less than 8 do not format
      // return same name
      return name;
    }
    newName = newName.substring(0, 8) + (name.length > 8 ? '[...]' : '');
    return newName + '.' + ext;
  }
}

Usage


this.fileName = 'angular-training.pdf';

<p title="{{fileName}}">{{fileName | truncate}}</p>

Result


angular-[...].pdf

Here we have created a simple pipe. You can use this pipe anywhere in your angular application. It will truncate the file name without hiding the extension. You can update […] this to (…) or any other way you want. As we added a title user can hover and see the full file name as well.

In this article we have discussed about creating a simple truncate pipe to truncate the file name without hiding its extension.

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project

2. How to create an Angular application from scratch with simple steps.

3. How to create and use shared module in angular application.

1 comment :