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 {}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…