Skip to content Skip to sidebar Skip to footer

How To Cut Short Long Strings While Rendering Using Typescript

I'm sorry for asking a very stupid question. It should be very easy but I'm not able to do this. I'm creating a minimal working model on stackblitz. So, I've a string array contain

Solution 1:

You can derive your own pipe EllipsisPipe from SlicePipe. In the code below, the derived pipe calls super.transform to apply slice:0:maxLength, and appends the ellipsis if the original string is longer than maxLength. Please note that super refers to the parent class SlicePipe.

import { Pipe } from'@angular/core';
import { SlicePipe } from'@angular/common';

@Pipe({
  name: 'ellipsis'
})
exportclassEllipsisPipeextendsSlicePipe {
  constructor () {
    super();
  }
  transform(value: string, maxLength: number): any {
    const suffix = value && value.length > maxLength ? "..." : "";
    returnsuper.transform(value, 0, maxLength) + suffix;    
  }
}

The pipe can then be used in the template:

{{ token | ellipsis:15 }}

See this stackblitz for a demo.


Update

If the items are displayed inside a PrimeNG Chips component, you can define a custom template and apply the EllipsePipe in the template:

<p-chips [(ngModel)]="values"><ng-templatelet-itempTemplate="item">
    {{item | ellipsis:15}}
  </ng-template></p-chips>

See this stackblitz for a demo.

Solution 2:

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'
})

exportclassTruncatePipeimplementsPipeTransform {

transform(value: string, args: string[]): 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 classAppModule {}

Here is stackblitz You can check here


Different way using css


.b {
  white-space: nowrap; 
  width: 60px;  /* you can do with the help of width  */overflow: hidden;
  text-overflow: ellipsis; 
}
<divclass="b">Hello world!</div>

Post a Comment for "How To Cut Short Long Strings While Rendering Using Typescript"