How to concat a string after using slice pipe

点点圈 提交于 2020-04-30 06:08:05

问题


I'm new to Angular. I want to cut short strings that are longer than 15 characters (say) and then add ... at the end.

For eg:

Name: Tanzeel,

Role: Intern

Address: Bangal...,

Likes: C, CPP, ...,

I'm using p-chips from PrimeNg to display some tags. I'm not getting any error. Actually I'm not getting anything, my web page is just blank. Even the console log is also clean. Here's my code:

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

And here's the stackblitz for the same. The code works when I remove +... but then there was no ... concatenation seen (obviously). Please point of my mistake. However, In a separate branch, I created my own custom pipe for the same from this question:

How to cut short long strings while rendering using Typescript

And here's the code.

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

And It is working perfectly. You can see the stackblitz for this also. But when I showed this to my Tech lead, She called me an idiot for re-inventing the wheel. :-( She told me to use slice or anything which is provided by Angular itself. Please correct my mistake. (Please pardon me If I'm really asking a stupid question).

P.S: I got some help from this - How to truncate text in Angular2?


回答1:


From Angular documentation: it does not provide an option to add ellipsis at the end of string. So if you want to add ellipsis, I think your custom pipe is the only solution. In our project we also use custom pipe similar to yours.

And for why your attempt does not work:

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

It is not working because you're passing invalid parameter.

https://angular.io/api/common/SlicePipe - you can see here it only accepts numbers, but you're passing 15... (string).

A simple solution (using only Angular's slice pipe) would be:

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

Or:

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

But this is hardcoded so I suggest to use your custom pipe instead.



来源:https://stackoverflow.com/questions/61040964/how-to-concat-a-string-after-using-slice-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!