Mohit Pandey
Mohit Pandey

Reputation: 131

How to truncate text in Angular?

I want to show smaller text. I see options like making custom pipe for truncating string but my case is different as follows.

<p [innerHTML]="aboutUs"></p>

In this I can't use a custom pipe. I'm doing this because I show text from backend & it comes with tags that's why [innerHtml] is used. Please help.

Upvotes: 3

Views: 6682

Answers (2)

prabhatojha
prabhatojha

Reputation: 2085

Avoid using a method call from HTML template as it will be called a lot of times, which would be unnecessary processing if the desired result is static or not modified very often.

Call the method truncateChar(in @Sajeetharan answer) from any of ngOnInit, ngOnChange or wherever you are updating the aboutUs variable and save the result in some variable in that component.

Use this variable in your template instead of calling the method directly.

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222522

You can do with a custom function using TypeScript as,

truncateChar(text: string): string {
    let charlimit = 100;
    if(!text || text.length <= charlimit )
    {
        return text;
    }

  let without_html = text.replace(/<(?:.|\n)*?>/gm, '');
  let shortened = without_html.substring(0, charlimit) + "...";
  return shortened;
}

and in the HTML refer it as,

<div [innerHTML]="truncateChar(aboutUs)"></div>

Upvotes: 7

Related Questions