如何在 Angular2 中截断文本?

是否有一种方法,我可以限制字符串的长度为一个数字字符? 例如:我必须限制标题长度为 20 {{ data.title }}.

是否有管道或过滤器可以限制文本长度?

218887 次浏览

两种方法将文本截断成角。

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

1. 解决方案

  \{\{str | slice:0:6}}

输出:

   how to

如果你想在切片字符串之后追加任何文本,比如

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

输出:

 how to...

2. 解决方案(创建自定义管道)

如果要创建自定义截断管道

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;
}
}

在标记

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

不要忘记添加一个模块条目。

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

可选参数截断管道:

  • 限制 - string最大长度
  • completeWords -标记截断最近的完整单词,而不是字符
  • 省略 -附加尾后缀

-

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


@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
if (completeWords) {
limit = value.substr(0, limit).lastIndexOf(' ');
}
return value.length > limit ? value.substr(0, limit) + ellipsis : value;
}
}

不要忘记添加一个模块条目。

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

使用

示例字符串:

public longStr = 'A really long string that needs to be truncated';

标记:

  <h1>\{\{longStr | truncate }}</h1>
<!-- Outputs: A really long string that... -->


<h1>\{\{longStr | truncate : 12 }}</h1>
<!-- Outputs: A really lon... -->


<h1>\{\{longStr | truncate : 12 : true }}</h1>
<!-- Outputs: A really... -->


<h1>\{\{longStr | truncate : 12 : false : '***' }}</h1>
<!-- Outputs: A really lon*** -->

如果你想用字数截断并添加省略号,你可以使用这个函数:

truncate(value: string, limit: number = 40, trail: String = '…'): string {
let result = value || '';


if (value) {
const words = value.split(/\s+/);
if (words.length > Math.abs(limit)) {
if (limit < 0) {
limit *= -1;
result = trail + words.slice(words.length - limit, words.length).join(' ');
} else {
result = words.slice(0, limit).join(' ') + trail;
}
}
}


return result;
}

例子:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 5, '…')
> "Bacon ipsum dolor amet sirloin…"
< p > < em >摘自: https://github.com/yellowspot/ng2-truncate/blob/master/src/truncate-words.pipe.ts < / em > < / p >

如果你想用字母数截断,但不删减单词,使用以下方法:

truncate(value: string, limit = 25, completeWords = true, ellipsis = '…') {
let lastindex = limit;
if (completeWords) {
lastindex = value.substr(0, limit).lastIndexOf(' ');
}
return `${value.substr(0, limit)}${ellipsis}`;
}

例子:

truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, true, '…')
> "Bacon ipsum dolor…"


truncate('Bacon ipsum dolor amet sirloin tri-tip swine', 19, false, '…')
> "Bacon ipsum dolor a…"

我一直在使用这个模块喜欢的《忍者外传2》截断,它非常简单,导入模块和u已经准备好了…在\{\{data。标题| truncate: 20}}

刚刚尝试了@蒂莫西佩雷斯的回答,并添加了一行

if (value.length < limit)
return `${value.substr(0, limit)}`;

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


@Pipe({
name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {


if (value.length < limit)
return `${value.substr(0, limit)}`;


if (completeWords) {
limit = value.substr(0, limit).lastIndexOf(' ');
}
return `${value.substr(0, limit)}${ellipsis}`;
}
}

您可以根据CSS截断文本。它有助于根据宽度截断文本,而不是固定字符。

例子

CSS

.truncate {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}


.content {
width:100%;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

超文本标记语言

<div class="content">
<span class="truncate">Lorem Ipsum is simply dummied text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
</div>

注意:这段代码一行使用full,而不是多行。

如果你想用Angular来做,那么Ketan的解决方案是最好的

下面是另一种方法,使用interface来描述要通过标记中的pipe传递的选项对象的形状。

@Pipe({
name: 'textContentTruncate'
})
export class TextContentTruncatePipe implements PipeTransform {


transform(textContent: string, options: TextTruncateOptions): string {
if (textContent.length >= options.sliceEnd) {
let truncatedText = textContent.slice(options.sliceStart, options.sliceEnd);
if (options.prepend) { truncatedText = `${options.prepend}${truncatedText}`; }
if (options.append) { truncatedText = `${truncatedText}${options.append}`; }
return truncatedText;
}
return textContent;
}


}


interface TextTruncateOptions {
sliceStart: number;
sliceEnd: number;
prepend?: string;
append?: string;
}

然后在你的标记中:

\{\{someText | textContentTruncate:{sliceStart: 0, sliceEnd: 50, append: '...'} }}

使用切片管道(angular的核心管道)非常简单,就像你要求data.title一样:

\{\{ data.title | slice:0:20 }}

来自Angular公共文档https://angular.io/api/common/SlicePipe

根据单词限制长度

如果您想根据单词而不是字符进行截断,同时还允许一个选项查看完整的文本,可以试试这个方法。

来到这里搜索一个基于单词的阅读更多解决方案,分享自定义Pipe我最终写。

管:

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


@Pipe({
name: 'readMore'
})
export class ReadMorePipe implements PipeTransform {


transform(text: any, length: number = 20, showAll: boolean = false, suffix: string = '...'): any {
    

if (showAll) {
return text;
}


if ( text.split(" ").length > length ) {
      

return text.split(" ").splice(0, length).join(" ") + suffix;
}


return text;
}


}

在模板:

<p [innerHTML]="description | readMore:30:showAll"></p>
<button (click)="triggerReadMore()" *ngIf="!showAll">Read More<button>

组件:

export class ExamplePage implements OnInit {


public showAll: any = false;
    

triggerReadMore() {
this.showAll = true;
}
    

}

在模块:

import { ReadMorePipe } from '../_helpers/read-more.pipe';


@NgModule({
declarations: [ReadMorePipe]
})
export class ExamplePageModule {}

是这样的:

\{\{ data.title | slice:0:20 }}

如果你想要省略号,这里有一个变通方法

\{\{ data.title | slice:0:20 }}...
import { Pipe, PipeTransform } from '@angular/core';


@Pipe({
name: 'truncate',
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit: number, trail = '...'): string {
if (value.length <= limit) {
return value;
}


return value.substring(0, limit - trail.length).replace(/\s+$/, '') + trail;
}
}
\{\{ str | truncate: 20 }}
\{\{ str | truncate: 20:'>>>'] }}

如果需要用单词截断:

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


@Pipe({
name: 'truncateByWords',
})
export class TruncateByWordsPipe implements PipeTransform {
transform(value: string, limit: number, trail = '...'): string {
if (value.length <= limit) {
return value;
}


const substr = value.substring(0, limit - trail.length).split(' ');
const isLastWordFull = value
.split(' ')
.find(w => w === substr[substr.length - 1]);


if (isLastWordFull) {
return substr.join(' ') + trail;
}


return substr.slice(0, -1).join(' ') + trail;
}
}
\{\{ str | truncateByWords: 20 }}
\{\{ str | truncateByWords: 20:'>>>'] }}

为了获得更多的灵活性,如果我们想从结尾或开始截断(基于@Nika Kasradze):

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[1], 10) : 20;
const trail = args.length > 1 ? args[3] : '...';
return value.length > limit ? (args[2] === 'start' ? trail : '') + value.substr(args[0], limit) + (args[2] === 'end' ? trail : '') : value;
}
}

如何使用?

\{\{ myLongText | truncate:[20, myLongText.length-20, 'start', '...'] }}

用省略号截断字符串

不需要任何额外的管道,你可以使用切片。

\{\{ stringText | slice: 0:25}} \{\{ stringText.length > 25 ? '...' : ''}}