如何在使用Typescript进行渲染时削减短长字符串 [英] How to cut short long strings while rendering using Typescript

查看:75
本文介绍了如何在使用Typescript进行渲染时削减短长字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉提出一个非常愚蠢的问题.这应该很容易,但是我无法做到这一点.我正在 stackblitz 上创建一个最小的工作模型.因此,我有一个字符串数组,其中包含有关我的一些信息(例如).我想使用 ngFor 逐一显示它们.但是有些元素的字符串会很长.

I'm sorry for asking a very stupid question. It should be very easy but I'm not able to do this. I'm creating a minimal working model on stackblitz. So, I've a string array containing some information about me (say). I want to display them one by one using ngFor. But there will be some elements whose strings are very long.

例如:字符串为:

苹果,球,猫,狗,大象,鱼,山羊,母鸡,墨水,Jack狼,风筝

Apple, Ball, Cat, Dog, Elephant, Fish, Goat, Hen, Ink, Jackal, Kite

显示的文字应为:

苹果,鲍尔...

Apple, Ball ...

这意味着在第二个逗号 之后,或者可能在某些字符(例如15个字符)之后,应该为 ... ,因为原始文本占据较大的宽度

That means after the second comma , or may be after certain characters, say 15 characters, it should be ... because the original text is occupying a large width.

我尝试了以下方法:

  1. 切片(开始,结束)
  2. 子字符串(开始,结束)
  3. substr(开始,长度)

但是这些方法将永久缩短文本.我不要希望我能够解释这个问题.请纠正我.这是 stackblitz .

But these methods will permanently cut short the text. I don't want that. Hope I was able to explain the problem. Please correct me. Here's the stackblitz.

推荐答案

您可以从 SlicePipe 派生自己的管道 EllipsisPipe .在下面的代码中,派生管道调用 super.transform 以应用 slice:0:maxLength ,如果原始字符串长于 maxLength .请注意, super 引用父类 SlicePipe .

You can derive your own pipe EllipsisPipe from SlicePipe. In the code below, the derived pipe calls super.transform to apply slice:0:maxLength, and appends the ellipsis if the original string is longer than maxLength. Please note that super refers to the parent class SlicePipe.

import { Pipe } from '@angular/core';
import { SlicePipe } from '@angular/common';

@Pipe({
  name: 'ellipsis'
})
export class EllipsisPipe extends SlicePipe {
  constructor () {
    super();
  }
  transform(value: string, maxLength: number): any {
    const suffix = value && value.length > maxLength ? "..." : "";
    return super.transform(value, 0, maxLength) + suffix;    
  }
}

然后可以在模板中使用管道:

The pipe can then be used in the template:

{{ token | ellipsis:15 }}

请参见此stackblitz进行演示.

更新

如果项目显示在PrimeNG 芯片组件内部,则可以定义一个自定义模板并在模板中应用 EllipsePipe :

If the items are displayed inside a PrimeNG Chips component, you can define a custom template and apply the EllipsePipe in the template:

<p-chips [(ngModel)]="values">
  <ng-template let-item pTemplate="item">
    {{item | ellipsis:15}}
  </ng-template>
</p-chips>

请参见此stackblitz 演示.

这篇关于如何在使用Typescript进行渲染时削减短长字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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