如何在Angular2中截断文本?


126

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

是否有任何管道或过滤器限制长度?

Answers:


380

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

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

哪种解决方案性能良好。解决方案1或解决方案2。我认为解决方案1的性能不错。
Rigin Oommen '18

您可能要向return语句添加一个空检查,就我而言,我传入的是空字符串,这导致我的应用崩溃。 return value && value.length > limit ? value.substring(0, limit) + trail : value;
野蛮锤

@ketan:先生,我尝试了两种解决方案都可以正常工作,但是我的情况不同,我们最初显示了50个字符,单击更多链接后将显示更多文本,因此请告诉我上面的可能吗?
卡皮尔·索尼

在解决方案2中,transform(value: string, args: string[]): string应该是transform(value: string, args: any[]): string因为给管道的第一个参数是一个数字。
MattOnyx

:科坦你好,可以请你回答这个stackoverflow.com/questions/61040964/...
Tanzeel

83

使用可选参数截断管道:

  • 限制 -字符串最大长度
  • 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*** -->

7
感谢提供管道,limit = value.substr(0, 13).lastIndexOf(' ');应该是limit = value.substr(0, limit).lastIndexOf(' ');
Tomnar

1
您还可以添加以下内容:if (!value) { return ''; }if (value.length <= limit) { return value; }
JarekSzczepański18年

我也必须将其添加到@ngModule的导出部分,以使其正常工作。不知道为什么
tibi

@tibi就像一个新组件一样,您需要对其进行声明(声明数组)才能使用它。
calios '19

1
为了避免在不必要的值后面加上省略号,请使用`if(value.length <limit){返回值;}其他{return ${value.substr(0, limit)}${ellipsis}; }`
jabu.hlong

14

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

的CSS

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

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

的HTML

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

注意:此代码在一行中全部使用,最多使用一行。

如果您想通过Angular做到,最好的是Ketan解决方案


2
这个。一千倍!
brunner

完美的无障碍环境
Antonello Pasella


3

这是一种使用的替代方法,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: '...'} }}


1

如果要截断多个单词并添加省略号,则可以使用以下功能:

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…"

摘自:https : //github.com/yellowspot/ng2-truncate/blob/master/src/truncate-words.pipe.ts

如果您想截断多个字母但不删节,请使用以下命令:

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…"

1

刚刚尝试过@Timothy Perez答案并添加了一行

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

0

如果要基于单词而不是字符截断,请尝试执行此操作,同时还可以选择查看全文。

来到这里寻找基于单词Read More解决方案,分享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 {}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.