如何截断Angular2中的文本?

问题描述 投票:82回答:6

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

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

angular angular2-template
6个回答
263
投票

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

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

在标记

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

不要忘记添加模块条目。

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

54
投票

使用可选参数截断管道:

  • limit - 字符串最大长度
  • 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.substr(0, limit)}${ellipsis}`;
  }
}

不要忘记添加模块条目。

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

4
投票

您可以根据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 dummy 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的解决方案是最好的


3
投票

我一直在使用这个模块ng2 truncate,它非常简单,导入模块,你准备好了... {{data.title |截断:20}}


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

0
投票

刚尝试了@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}`;
}
}
© www.soinside.com 2019 - 2024. All rights reserved.