如何在 Angular2 中截断文本? [英] How to truncate text in Angular2?

查看:23
本文介绍了如何在 Angular2 中截断文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way that I could limit the length of the string to a number characters? for e.g: I have to limit a title length to 20 {{ data.title }}.

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

Is there any pipe or filter to limit the length?

推荐答案

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

Two way to truncate text into angular.

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.解决方案(创建自定义管道)

如果你想创建自定义截断管道

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

在标记中

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

不要忘记添加模块条目.

Don't forget to add a module entry.

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

这篇关于如何在 Angular2 中截断文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆