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

查看:91
本文介绍了如何截断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

别忘了添加模块条目.

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

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

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