How to truncate text in Angular2?

him picture him · Jun 21, 2017 · Viewed 142.3k times · Source

Is there a way that I could limit the length of the string to a number characters? for e.g: I have to limit a title length to 20 {{ data.title }}.

Is there any pipe or filter to limit the length?

Answer

Ketan Akbari picture Ketan Akbari · Jun 21, 2017

Two way to truncate text into angular.

let str = 'How to truncate text in angular';

1. Solution

  {{str | slice:0:6}}

Output:

   how to

If you want to append any text after slice string like

   {{ (str.length>6)? (str | slice:0:6)+'..':(str) }}

Output:

 how to...

2. Solution(Create custom pipe)

if you want to create custom truncate pipe

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

@Pipe({
 name: 'truncate'
})

export class TruncatePipe implements PipeTransform {

transform(value: string, args: any[]): string {
    const limit = args.length > 0 ? parseInt(args[0], 10) : 20;
    const trail = args.length > 1 ? args[1] : '...';
    return value.length > limit ? value.substring(0, limit) + trail : value;
   }
}

In Markup

{{ str | truncate:[20] }} // or 
{{ str | truncate:[20, '...'] }} // or

Don't forget to add a module entry.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}