代码之家  ›  专栏  ›  技术社区  ›  Tanzeel

如何在使用切片管道后连接字符串

  •  1
  • Tanzeel  · 技术社区  · 5 年前

    我是新来的角度。我想剪短超过15个字符的字符串,然后添加 ... 最后。

    姓名:Tanzeel,

    地址:孟加拉。。。,

    喜欢:C,CPP。。。,

    我在用 p-chips

    <p-chips [(ngModel)]="tokens">
      <ng-template let-item pTemplate="item">
        {{item | slice:0:15+'...'}}
      </ng-template>
    </p-chips>
    

    这里是 stackblitz 同样的。代码在我移除 +... 但后来没有 ...

    椭圆spipe.component.ts

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

    它工作得很好。你可以看到 stackblitz 也为了这个。但当我把这个展示给我的技术主管时,她说我是个白痴,因为我重新发明了轮子。(她让我用 slice

    P、 S:我得到了一些帮助- How to truncate text in Angular2?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Gynteniuxas hrboy    5 年前

    来自角度文档:它不提供在字符串末尾添加省略号的选项。所以如果你想添加省略号,我认为你的自定义管道是唯一的解决方案。在我们的项目中,我们也使用与您类似的自定义管道。

    为什么你的尝试没有成功:

    {{item | slice:0:15+'...'}}
    

    https://angular.io/api/common/SlicePipe -你可以看到这里它只接受数字,但是你传递 15... (字符串)。

    slice 管道)将是:

    {{ item | slice:0:15 }}...
    

    或:

    {{ (item | slice:0:15) + '...' }}
    

    但这是硬编码的,所以我建议改用您的自定义管道。

    推荐文章